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 we don't implement `eat` method, a compilation error happens
@Override
public void eat(String food) {
System.out.println("The student is eating " + food);
}
}
class Employee extends Person {
// If we don't implement `eat` method, a compilation error happens
@Override
public void eat(String food) {
System.out.println("The employee is eating " + food);
}
}
class Main {
public static void main(String[] args) {
Student student = new Student();
student.eat("sandwich");
Employee employee = new Employee();
employee.eat("banana");
}
}
Comments
Leave a comment