Inheritance and Polymorphism · Lesson 23 of 42
Inheritance and super
Inheritance lets a new class reuse an existing one and add or change only what is different. A Manager is an Employee with a bonus; a SavingsAccount is an Account with interest. Instead of copying code, the child class extends the parent and inherits its fields and methods.
In this lesson
extends: parent and child classessuperfor constructors and parent methods- The constructor chain and the
Objectclass - Types of inheritance, and is-a vs has-a
A parent and a child
public class Main {
public static void main(String[] args) {
Manager m = new Manager("Ravi", 90000, 15000);
System.out.println(m.getName() + " earns ₹" + m.annualPay() + " a year");
System.out.println(m.describe());
}
}
class Employee {
private final String name;
protected double monthlySalary;
Employee(String name, double monthlySalary) {
this.name = name;
this.monthlySalary = monthlySalary;
}
String getName() { return name; }
double annualPay() { return monthlySalary * 12; }
String describe() { return getName() + " (Employee)"; }
}
class Manager extends Employee { // Manager IS-AN Employee
private final double monthlyBonus;
Manager(String name, double salary, double bonus) {
super(name, salary); // let Employee initialise its part
this.monthlyBonus = bonus;
}
@Override
double annualPay() {
return super.annualPay() + monthlyBonus * 12; // reuse the parent's logic
}
@Override
String describe() { return getName() + " (Manager, bonus ₹" + monthlyBonus + ")"; }
}
Ravi earns ₹1260000.0 a year Ravi (Manager, bonus ₹15000.0)
What Manager gets
Employee: name, monthlySalary, getName(), annualPay(), describe()
- InheritedgetName(), monthlySalary (protected)
- OverriddenannualPay(), describe()
- AddedmonthlyBonus
The child inherits every non-private member. Private fields like name exist inside a Manager object, but only Employee's own methods can touch them – that's why Manager uses getName().
super
super(...)calls the parent constructor. It must be the first statement of the child constructor.super.method()calls the parent's version of an overridden method.- If you don't write
super(...), Java insertssuper()automatically – which fails to compile if the parent has no no-argument constructor.
The constructor chain
Creating a child object runs constructors from the top of the hierarchy down. Every class ultimately extends java.lang.Object.
public class Main {
public static void main(String[] args) {
new Puppy();
}
}
class Animal {
Animal() { System.out.println("1. Animal constructor"); }
}
class Dog extends Animal {
Dog() { System.out.println("2. Dog constructor"); }
}
class Puppy extends Dog {
Puppy() { System.out.println("3. Puppy constructor"); }
}
1. Animal constructor 2. Dog constructor 3. Puppy constructor
Hierarchy (constructors run top to bottom)
- Objectroot of every class
- Animalextends Object implicitly
- Dogextends Animal
- Puppyextends Dog
Types of inheritance
| Type | Example | In Java? |
|---|---|---|
| Single | Manager extends Employee | Yes |
| Multilevel | Puppy → Dog → Animal | Yes |
| Hierarchical | Car and Bike both extend Vehicle | Yes |
| Multiple (classes) | class C extends A, B | No – use interfaces |
Interview angle: why no multiple inheritance of classes?
The "diamond problem": if B and C both override a method from A, and D extended both, which version would D inherit? Java avoids the ambiguity for classes. A class can implement many interfaces instead, and if two interfaces supply the same default method, the compiler forces you to choose (chapter 10).
is-a vs has-a
Use inheritance only for a true is-a relationship. When one object merely has or uses another, store it as a field – this is composition, and experienced developers prefer it whenever inheritance doesn't clearly fit.
public class Main {
public static void main(String[] args) {
Car car = new Car("Nexon EV", new Engine(143));
System.out.println(car.start());
}
}
class Engine {
private final int hp;
Engine(int hp) { this.hp = hp; }
String start() { return hp + " hp engine started"; }
}
class Car { // a Car HAS-AN Engine (composition)
private final String model;
private final Engine engine;
Car(String model, Engine engine) {
this.model = model;
this.engine = engine;
}
String start() { return model + ": " + engine.start(); }
}
Nexon EV: 143 hp engine started
Common mistake: inheriting just to reuse code
class Order extends ArrayList<Item> gives Order every list method – including ones that break its rules, like clear(). An Order has items; keep a private list field and expose only the operations Order needs.
Practice
Try it yourself
Create
Account(owner, balance)andSavingsAccount extends AccountwithaddInterest(ratePercent).Show solution
public class Main { public static void main(String[] args) { SavingsAccount s = new SavingsAccount("Neel", 10000); s.addInterest(7); System.out.println(s.owner + " ₹" + s.balance); } } class Account { final String owner; double balance; Account(String owner, double balance) { this.owner = owner; this.balance = balance; } } class SavingsAccount extends Account { SavingsAccount(String owner, double balance) { super(owner, balance); } void addInterest(double rate) { balance += balance * rate / 100; } }Neel ₹10700.0
Quick check
Where must super(...) appear?
As the first statement of a constructor.
Does a child class inherit private fields?
The object contains them, but the child's code can't access them directly – it uses the parent's public/protected methods.
Should Order extend Customer?
No – an order has a customer (composition), it is not a kind of customer.
Summary
class Child extends Parentinherits non-private members;superreaches the parent.- Constructors run from
Objectdown to the child; Java has no multiple class inheritance. - Inherit for is-a, compose for has-a.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.