Chapter 05
Java Inheritance & Polymorphism
5 topics · 1 sections · beginner-friendly study notes · Updated
Inheritance lets a class reuse the members of another class.
Polymorphism lets the same method call behave differently depending on the actual object.
This chapter covers inheritance, method overriding, the super keyword, runtime polymorphism and the final keyword.
Inheritance and polymorphism produce flexible code and appear in every Java interview.
Framework base classes, payment gateways with many providers, GUI components, collections (List to ArrayList) and plug-in systems.
Inheritance in Java
Inheritance is the mechanism by which a child (subclass) class acquires the fields and methods of a parent (superclass) using the extends keyword. It represents an IS-A relationship and promotes code reuse.
In short: A child class gets everything of its parent for free and can add its own features.
Think about it
Reusing a tested parent class saves time and keeps common behaviour in one place. Savings and Current accounts both extend an Account class that holds the common balance logic.
Types supported with classes: single (B extends A), multilevel (C extends B extends A) and hierarchical (B and C both extend A).
Multiple inheritance of classes is not allowed because of the diamond problem; a class can implement many interfaces instead.
Hybrid inheritance is possible only through interfaces.
A subclass inherits public and protected members, and package-private members within the same package, but not private members (they exist in the object but are not accessible) and not constructors.
Every class without extends silently extends java.
lang.
When an object of the child is created, the parent constructor runs first (super() is called implicitly).
Use inheritance only for a true IS-A relationship; for HAS-A use composition.
Cyclic inheritance is a compile error.
The advantages are reuse, extensibility and polymorphism; the drawback is tight coupling between parent and child.
Key points
- Superclass: Parent class being extended.
- Subclass: Child class that extends another class.
- IS-A: Relationship expressed by inheritance.
- Diamond problem: Ambiguity when two parents provide the same member.
- extends: Keyword used to inherit from a class.
- Java supports single, multilevel and hierarchical inheritance with classes.
- Multiple inheritance of classes is not supported; use interfaces.
- Private members are not inherited (not accessible).
- Constructors are not inherited, but the parent constructor always runs first.
Read more
Example
Codesingle, multilevel and hierarchical:
class Animal {
String name;
Animal(String name) {
this.name = name;
System.out.println("Animal constructor");
}
void eat() { System.out.println(name + " eats"); }
}
class Dog extends Animal { // single inheritance
Dog(String name) {
super(name);
System.out.println("Dog constructor");
}
void bark() { System.out.println(name + " barks"); }
}
class Puppy extends Dog { // multilevel
Puppy(String name) {
super(name);
System.out.println("Puppy constructor");
}
void weep() { System.out.println(name + " weeps"); }
}
class Cat extends Animal { // hierarchical (Dog and Cat share Animal)
Cat(String name) { super(name); }
void meow() { System.out.println(name + " meows"); }
}
public class InheritanceDemo {
public static void main(String[] args) {
Puppy p = new Puppy("Bruno"); // Animal -> Dog -> Puppy constructors
p.eat(); // inherited from Animal
p.bark(); // inherited from Dog
p.weep(); // own method
Cat c = new Cat("Kitty");
c.eat();
c.meow();
System.out.println(p instanceof Animal); // true (IS-A)
System.out.println(p.toString().startsWith("Puppy")); // Object.toString
}
}Method Overriding in Java
Method overriding means a subclass provides its own implementation of a method that is already defined in its superclass, with the same name, the same parameters and a compatible return type.
In short: The child rewrites a method it inherited because it needs different behaviour.
Think about it
Overriding is how a child customises inherited behaviour and makes run-time polymorphism possible. Every class overrides toString() to print itself; a Manager overrides calculateSalary() to add a bonus.
Rules: 1) same method name and parameter list; 2) return type must be the same or a covariant (subtype) type; 3) access cannot be weaker (public can only be overridden by public); 4) it cannot throw broader checked exceptions; 5) private, static and final methods cannot be overridden (static methods are hidden); 6) constructors cannot be overridden.
Always add @Override so the compiler checks your signature.
Overriding is resolved at run time based on the actual object (dynamic binding).
A method with the same name but different parameters is overloading, not overriding.
A subclass can still call the parent version using super.
method().
Overriding Object methods such as toString(), equals() and hashCode() is very common.
Fields are not overridden; a same-named field in the child hides the parent field.
Key points
- @Override: Annotation that asks the compiler to verify overriding.
- Covariant return: Overriding method may return a subtype.
- Dynamic binding: Method chosen at run time from the actual object.
- Method hiding: A static method in the child hides the parent static method.
- Overriding needs inheritance; overloading does not.
- Access level can be widened but never narrowed.
- static, private and final methods cannot be overridden.
- Use @Override on every overriding method.
Example
Codeoverriding rules in action:
class Bank {
double rate() { return 5.0; }
Number maxLoan() { return 100000; }
static void info() { System.out.println("Bank info"); }
public String toString() { return "Generic bank"; }
}
class Sbi extends Bank {
@Override
double rate() { return 6.5; }
@Override
Integer maxLoan() { return 500000; } // covariant return type
static void info() { System.out.println("Sbi info"); } // hiding, not overriding
@Override
public String toString() { return "SBI at rate " + rate(); }
}
class Hdfc extends Bank {
@Override
double rate() { return 7.1; }
}
public class OverridingDemo {
public static void main(String[] args) {
Bank b1 = new Bank();
Bank b2 = new Sbi();
Bank b3 = new Hdfc();
System.out.println(b1.rate()); // 5.0
System.out.println(b2.rate()); // 6.5
System.out.println(b3.rate()); // 7.1
System.out.println(b2); // SBI at rate 6.5
System.out.println(b2.maxLoan()); // 500000
b2.info(); // Bank info (static: decided by reference type)
Sbi.info(); // Sbi info
}
}super Keyword in Java
The super keyword is a reference to the immediate parent class. It is used to access a parent field, call a parent method that has been overridden, and call a parent constructor with super(...).
In short: super means "my parent". Use it when the child needs something from the parent.
Think about it
super lets the child reuse the parent code instead of copying it. A child toString() often returns super.toString() plus its own details.
Three uses: 1) super.
field accesses a parent field hidden by a child field of the same name.
2) super.
method() calls the parent version of an overridden method, useful to extend rather than replace behaviour.
3) super(...
) calls a parent constructor and must be the first statement.
If you do not write super(...
) the compiler inserts super() automatically; if the parent has no no-argument constructor, the child constructor must call super(args) explicitly or the code does not compile.
super and this cannot both be first calls in one constructor.
super cannot be used in a static context.
Since Java 8, Interface.
super.
method() lets a class choose which default method to call when two interfaces provide the same default method.
Key points
super(): Call to a parent constructor.super.method(): Call to the parent version of a method.- Implicit
super(): Compiler-inserted call when none is written. super(...)must be the first statement in the constructor.- If the parent lacks a no-argument constructor, call
super(args)explicitly. - super is not available in static methods.
Example
Codesuper for constructor, method and field:
class Person {
String name = "Person";
int age;
Person(String n, int a) {
name = n;
age = a;
}
void show() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
class Employee extends Person {
String name = "Employee"; // hides the parent field
double salary;
Employee(String n, int a, double s) {
super(n, a); // parent constructor (required: no default one)
this.salary = s;
}
@Override
void show() {
super.show(); // reuse parent code
System.out.println("Salary: " + salary);
}
void names() {
System.out.println("this.name = " + this.name); // Employee
System.out.println("super.name = " + super.name); // Asha
}
}
public class SuperDemo {
public static void main(String[] args) {
Employee e = new Employee("Asha", 28, 60000);
e.show();
e.names();
}
}Runtime Polymorphism in Java
Runtime polymorphism (dynamic method dispatch) is the process in which a call to an overridden method is resolved at run time, based on the actual object type, when a parent-class reference variable refers to a child-class object (upcasting).
In short: One parent reference can hold many kinds of child objects, and each object responds in its own way.
Think about it
It lets you add new types without changing existing code (open-closed principle). A payment() method accepts a PaymentMethod reference; it works for Card, UPI and Wallet objects alike.
Upcasting: Parent p = new Child(); is automatic and safe.
The compiler checks that the method exists in the reference type; the JVM then calls the version in the actual object.
Only methods are polymorphic: fields, static methods, private methods and overloaded methods use the reference type.
With an upcast reference you cannot call a child-only method; you need a downcast: ((Child) p).
childOnly().
A wrong downcast throws ClassCastException, so check with instanceof first (Java 16+ allows pattern matching: if (p instanceof Child c)).
The JVM implements dispatch with a virtual method table (vtable).
This is the basis of programming to interfaces: write code against a parent type and plug in any child.
Key points
- Upcasting: Assigning a child object to a parent reference.
- Downcasting: Casting a parent reference back to a child type.
- Dynamic dispatch: Choosing the method at run time.
- ClassCastException: Thrown by an invalid downcast.
- vtable: Table the JVM uses to find the overridden method.
- Methods are polymorphic; fields are not.
- Reference type decides what you can call; object type decides what runs.
- Use instanceof before a downcast.
- Static and private methods are never dynamically dispatched.
Read more
Example
Codeshapes with dynamic dispatch:
abstract class Shape {
String label = "Shape";
abstract double area();
void describe() {
System.out.println(getClass().getSimpleName() + " area = " + area());
}
}
class Circle extends Shape {
String label = "Circle";
double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
void radius() { System.out.println("Radius " + r); }
}
class Rect extends Shape {
double w, h;
Rect(double w, double h) { this.w = w; this.h = h; }
double area() { return w * h; }
}
public class PolymorphismDemo {
public static void main(String[] args) {
Shape[] shapes = { new Circle(2), new Rect(3, 4), new Circle(1) };
double total = 0;
for (Shape s : shapes) {
s.describe(); // runs the version of the real object
total += s.area();
}
System.out.printf("Total area = %.2f%n", total);
Shape s = new Circle(5);
System.out.println(s.label); // Shape (fields use the reference type)
// s.radius(); // error: not in Shape
if (s instanceof Circle) {
Circle c = (Circle) s; // safe downcast
c.radius();
}
Shape r = new Rect(1, 2);
try {
Circle bad = (Circle) r; // wrong downcast
} catch (ClassCastException e) {
System.out.println("ClassCastException caught");
}
}
}final Keyword in Java
The final keyword restricts change. A final variable can be assigned only once, a final method cannot be overridden and a final class cannot be extended.
In short: final means "no more changes allowed".
Think about it
final protects constants, critical behaviour and immutable designs from accidental change. API keys, maximum limits, tax rates and immutable value classes such as String.
final variable: a constant after first assignment.
A final local variable, field or parameter must be assigned exactly once.
A blank final field is assigned in the constructor or an initialiser block.
Constants are usually public static final with UPPER_CASE names, for example Math.
PI.
For a final reference variable the reference cannot change, but the object it points to can still change: final List<String> list = new ArrayList<>(); list.
add("x"); is legal while list = new ArrayList<>(); is not.
final method: prevents overriding and allows the compiler to optimise.
final class: prevents inheritance; String, Integer and other wrappers are final, which supports immutability and security.
A constructor cannot be final.
final is different from finally (a try block clause) and finalize() (an old, deprecated Object method).
Key points
- Constant: A final variable with a fixed value.
- Blank final: Final field not initialised at declaration.
- Immutable: An object whose state cannot change after creation.
- finally: Block that always runs after try-catch (a different thing).
- final reference = cannot point elsewhere; the object may still change.
- A final class cannot have subclasses; a final method cannot be overridden.
- final, finally and finalize() are three different things.
- A blank final field must be set in every constructor.
Read more
Example
Codefinal variable, method and class:
import java.util.ArrayList;
import java.util.List;
final class Currency { // cannot be extended
public static final String CODE = "INR"; // constant
private final double amount; // blank final
Currency(double amount) { this.amount = amount; }
double getAmount() { return amount; }
}
// class Rupee extends Currency {} // error: cannot inherit from final
class Vehicle {
final void start() { System.out.println("Engine started"); } // cannot be overridden
void stop() { System.out.println("Vehicle stops"); }
}
class Car extends Vehicle {
// void start() {} // error: cannot override final method
@Override void stop() { System.out.println("Car stops"); }
}
public class FinalDemo {
public static void main(String[] args) {
final int limit = 100;
// limit = 200; // error: cannot assign a value to final variable
System.out.println(limit + " " + Currency.CODE);
final List<String> names = new ArrayList<>();
names.add("Asha"); // allowed: object changes
names.add("Ravi");
// names = new ArrayList<>(); // error: reference is final
System.out.println(names);
new Car().start();
new Car().stop();
System.out.println(new Currency(250.5).getAmount());
}
}Solved examples
Class B extends A. A has constructor A() printing "A", B has constructor B() printing "B". What is printed by new B()?
Output order
Formula Applied:—Approach note: Parent constructors always run before the child constructor body.
class P { void f() { print("P"); } } class C extends P { void f() { print("C"); } } What does P p = new C(); p.f(); print?
Printed text
Formula Applied:—Approach note: Methods use the object type; fields use the reference type.
class P { int x = 10; } class C extends P { int x = 20; } What does P p = new C(); System.out.println(p.x); print?
Printed value
Formula Applied:—Approach note: Use ((C) p).x to reach the child field.
Animal a = new Dog(); a.speak(); where Animal.speak prints "..." and Dog overrides to print "woof". What prints and why?
Output and rule
Formula Applied:—Approach note: Overriding uses the object; overloading uses the reference at compile time.
Real-world applications
Using Java Inheritance & Polymorphism in real projects
Framework base classes, payment gateways with many providers, GUI components, collections (List to ArrayList) and plug-in systems.
Common mistakes
❌ Myth: Java supports multiple inheritance with classes.
Why this is wrong: Two parents would create the diamond problem.
✅ Verified Truth: A class extends one class but can implement many interfaces.
⚠️ Exam Tip: Say "multiple inheritance only through interfaces".
❌ Myth: Method overloading and overriding are the same.
Why this is wrong: Overloading is within one class with different parameters; overriding needs a parent and child with the same signature.
✅ Verified Truth: Overloading is compile-time; overriding is run-time.
⚠️ Exam Tip: Give the compile-time vs run-time contrast.
❌ Myth: A final object cannot change.
Why this is wrong: final only locks the reference.
✅ Verified Truth: The state of the object can still change unless it is immutable.
⚠️ Exam Tip: final reference vs immutable object.
❌ Myth: Static methods can be overridden.
Why this is wrong: They are bound to the class at compile time.
✅ Verified Truth: A static method in the child only hides the parent method.
⚠️ Exam Tip: Mention method hiding.
Revision notes
Inheritance lets a class reuse the members of another class. Polymorphism lets the same method call behave differently depending on the actual object. This chapter covers inheritance, method overriding, the super keyword, runtime polymorphism and the final keyword.
High-Yield Quick Revision Points
- Inheritance uses extends and gives IS-A relationship and code reuse.
- Supported with classes: single, multilevel, hierarchical; multiple inheritance through interfaces only.
- Parent constructor runs first; private members are not accessible in the child; constructors are not inherited.
- Overriding: same signature, covariant return, no weaker access, no broader checked exceptions.
- static, private and final methods cannot be overridden.
- super: parent field, parent method, parent constructor (first statement).
- Dynamic dispatch: methods follow the object; fields and static methods follow the reference.
- final: constant variable, no-override method, no-extend class; final reference can still change object state.
Practice questions
Which keyword is used to inherit a class?
Which cannot be overridden?
In Parent p = new Child(); which version of an overridden method runs?
Which statement must be first in a constructor when used?
What is thrown by an invalid downcast?
Which is true for a final class?