Video in progress

What is inheritance and how do you write it in Java?

Inheritance is when one class takes the fields and methods of another class and extends or changes them. In Java it is written with extends and expresses an "is-a" relationship: Dog extends Animal means a dog is an animal.

📖 Answer

public class Employee {
    protected final String name;
    public Employee(String name) { this.name = name; }
    public long monthlySalary() { return 5_000_000; }
}

public class Manager extends Employee {
    private final long bonus;
    public Manager(String name, long bonus) {
        super(name);          // call the parent constructor
        this.bonus = bonus;
    }
    @Override
    public long monthlySalary() { return super.monthlySalary() + bonus; }
}

Manager got the name field and the monthlySalary method, and rewrote the method to fit its own needs.

Limitations:

  • a class can extends only one class;
  • private members exist inside the object, but a child class can't access them directly;
  • constructors are not inherited;
  • all classes ultimately inherit from java.lang.Object.

Don't use inheritance just to "avoid duplicating code". Use it only when there is a real "is-a".