OOP and design · Topic 4 of 12
Inheritance
Definition​
Inheritance lets a class reuse and extend another class with extends. The child class gets the parent's fields and methods and can add new ones or change existing ones. Use it for a true "is-a" relationship.
Example code​
A manager is an employee with extras
class Employee {
protected final String name;
protected final int salary;
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
int yearlyPay() { return salary * 12; }
}
class Manager extends Employee {
private final int bonus;
Manager(String name, int salary, int bonus) {
super(name, salary); // reuse the parent's constructor
this.bonus = bonus;
}
@Override
int yearlyPay() { return super.yearlyPay() + bonus; } // change inherited behaviour
}
class Demo {
public static void main(String[] args) {
Employee dev = new Employee("Asha", 5_000);
Manager lead = new Manager("Ravi", 7_000, 10_000);
System.out.println(dev.name + " earns " + dev.yearlyPay());
System.out.println(lead.name + " earns " + lead.yearlyPay());
}
}
// Output:
// Asha earns 60000
// Ravi earns 94000
Finished this page? Track your progress (saved only in your browser).