Inheritance
Inheritance lets a new class reuse an existing class and add to it. The existing class is the superclass (parent); the new one is the subclass (child). The relationship is "is-a": a Car is a Vehicle, a Manager is an Employee.
class Employee {
String name;
double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
double annualPay() {
return salary * 12;
}
}
class Manager extends Employee {
double bonus;
Manager(String name, double salary, double bonus) {
super(name, salary); // run Employee's constructor first
this.bonus = bonus;
}
}
A Manager has name, salary and annualPay() from Employee, plus its own bonus.
Types of inheritance in Java
- Single:
B extends A. - Multilevel:
C extends B,B extends A. - Hierarchical:
BandCboth extendA. - Multiple inheritance of classes is not allowed: a class extends only one class. A class can implement many interfaces instead (see the next topic).
Every class that extends nothing automatically extends java.lang.Object.
super
super(...)calls the parent's constructor. It must be the first line of the child's constructor.- If you do not write it, Java inserts
super()(no arguments). That fails if the parent has no no-argument constructor. super.method()calls the parent's version of an overridden method.super.fieldreaches a parent field hidden by a child field of the same name.
Constructor chaining
Constructors run from the top of the family down:
class A { A() { System.out.println("A"); } }
class B extends A { B() { System.out.println("B"); } }
class C extends B { C() { System.out.println("C"); } }
new C(); // prints A, then B, then C
Method overriding
A subclass can give its own version of an inherited method. The name, parameters and return type must match.
class Manager extends Employee {
double bonus;
Manager(String name, double salary, double bonus) {
super(name, salary);
this.bonus = bonus;
}
@Override
double annualPay() {
return super.annualPay() + bonus; // reuse the parent's work
}
}
@Override asks the compiler to check that you really are overriding. A typo such as annualpay() then becomes a compile error instead of a silent new method.
Rules
- The overriding method cannot be less visible (a
publicmethod cannot becomeprivate). static,finalandprivatemethods are not overridden.- Overloading (same name, different parameters, same class) is decided at compile time; overriding (same signature, subclass) is decided at run time.
Polymorphism
Polymorphism means "many forms": one reference type, many actual object types, each behaving in its own way.
Employee[] staff = {
new Employee("Asha", 30000),
new Manager("Ravi", 50000, 100000)
};
for (Employee e : staff) {
System.out.println(e.name + ": " + e.annualPay());
}
Asha: 360000.0
Ravi: 700000.0
The variable type is Employee, but Java calls the annualPay() of the actual object. This is runtime polymorphism (dynamic method dispatch). New employee types can be added later without changing the loop.
Upcasting and downcasting
Employee e = new Manager("Ravi", 50000, 100000); // upcast: automatic
// e.bonus; // error: Employee has no bonus
if (e instanceof Manager m) { // check, then downcast (Java 16+)
System.out.println(m.bonus);
}
Before Java 16 you write if (e instanceof Manager) { Manager m = (Manager) e; ... }. A wrong downcast throws ClassCastException.
The Object class
Every class inherits these methods from Object; you often override them:
| Method | Default behaviour | Override to |
|---|---|---|
toString() | ClassName@hashcode | give a readable description |
equals(Object o) | same as == | compare contents |
hashCode() | based on the object's identity | match equals (needed for HashMap and HashSet) |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee other)) return false;
return name.equals(other.name) && salary == other.salary;
}
@Override
public int hashCode() {
return java.util.Objects.hash(name, salary);
}
Composition: "has-a"
Not everything should inherit. A Car has an Engine; it is not an engine. Use a field:
class Engine { int cc; Engine(int cc) { this.cc = cc; } }
class Car {
private final Engine engine = new Engine(1200);
}
Prefer composition when the "is-a" test fails.
Common mistakes
- Forgetting
super(...)when the parent has no no-argument constructor: "constructor Employee in class Employee cannot be applied". - Misspelling an overridden method without
@Override, so the parent's version still runs. - Trying
class C extends A, B: Java allows only one superclass. - Calling a child-only method through a parent-type variable without casting.
- Overriding
equalsbut nothashCode, which breaksHashSetandHashMap.
Key points
extendscreates an is-a relationship; a class has exactly one superclass.super(...)runs the parent constructor first;super.m()calls the parent's method.- Overriding replaces an inherited method;
@Overridelets the compiler check it. - A parent-type variable can hold any child object, and the child's override runs: runtime polymorphism.
- Use
instanceofbefore downcasting; overridetoString,equalsandhashCodeas needed.
Practice questions
1. What is printed by new C(); if A, B and C each print their letter in the constructor and C extends B extends A?
A, B, C: parent constructors run first.
2. Difference between overloading and overriding?
Overloading: same name, different parameter lists, usually in one class, chosen at compile time. Overriding: same name and parameters in a subclass, replacing the parent's version, chosen at run time.
3. Write Shape with double area() returning 0, and Circle that overrides it.
class Shape {
double area() { return 0; }
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
@Override
double area() { return Math.PI * r * r; }
}4. Given Shape s = new Circle(2);, which area() runs, and why?
Circle's, because Java picks the overridden method from the actual object at run time.
5. Why does class Dog extends Animal, Pet not compile?
Java does not allow a class to extend more than one class. Pet should be an interface: class Dog extends Animal implements Pet.