Declare the Person superclass as abstract. Add this abstract method to the class:
public abstract void eat(String food);
Both the Student and Employee class inherit from abstract superclass Person, and provides an implementation for eat() which displays that the student or employee is eating a certain food.
(Note what happens if you don’t implement eat().)
abstract class Person {
public abstract void eat(String food);
}
class Student extends Person {
// If `eat` is not implemented, then a compilation error happens
public void eat(String food) {
System.out.println("The student is eating " + food);
}
}
class Employee extends Person {
// If `eat` is not implemented, then a compilation error happens
public void eat(String food) {
System.out.println("The employee is eating " + food);
}
}
class Test {
public static void main(String[] args) {
Student student = new Student();
student.eat("cheese");
Employee employee = new Employee();
employee.eat("soup");
}
}
Comments
Leave a comment