Introduction & Syntax
Inheritance · Study material
Inheritance lets one class acquire the fields and methods of another. With class Car extends Vehicle, every Car automatically has everything a Vehicle has, and adds or refines what is special about cars. Inheritance models an IS-A relationship (a Car is a Vehicle, a SavingsAccount is an Account), removes duplicated code, and is the foundation for polymorphism – treating a Manager, an Intern and a SalesExecutive all as Employees. Java supports single, multilevel and hierarchical inheritance of classes (every class ultimately extends java.lang.Object), uses super to reach the parent's constructor, methods and fields, and deliberately forbids extending two classes at once. Knowing when not to inherit – preferring composition (HAS-A) – is just as important. This page explains it all with programs you can run. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – compiled and run on Java 21.
On this page
- extends, superclass and subclass, IS-A
- What is inherited – and what is not
- super(...) and constructor chaining
- super.method() and super.field
- Single, multilevel and hierarchical inheritance; no multiple inheritance of classes
- Upcasting, downcasting and instanceof; composition vs inheritance
Syntax
class Vehicle { // superclass (parent, base class)
protected String brand;
protected int wheels;
void start() { System.out.println(brand + " engine started"); }
String info() { return brand + " with " + wheels + " wheels"; }
}
class Car extends Vehicle { // subclass (child, derived class): a Car IS-A Vehicle
int seats;
void openBoot() { System.out.println(brand + " boot opened"); } // new behaviour
}
class Bike extends Vehicle {
boolean hasCarrier;
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.brand = "Tata"; // inherited field
car.wheels = 4;
car.seats = 5; // its own field
car.start(); // inherited method
car.openBoot();
Bike bike = new Bike();
bike.brand = "Hero";
bike.wheels = 2;
System.out.println(car.info() + ", " + car.seats + " seats | " + bike.info());
}
}
Tata engine started Tata boot opened Tata with 4 wheels, 5 seats | Hero with 2 wheels
What is inherited?
| Member of the superclass | Inherited by the subclass? |
|---|---|
| public and protected fields and methods | yes |
| package-private members | only if the subclass is in the same package |
| private fields and methods | no – they exist inside the object but the subclass cannot access them directly |
| constructors | never – the subclass calls them with super(...) |
| static members | accessible through the subclass, but they still belong to the superclass |
Constructors and super(...)
Creating a subclass object always builds the superclass part first. Every constructor starts with either this(...) or super(...); if you write neither, the compiler inserts super() – which fails to compile when the parent has no no-arg constructor. So constructors run from the top of the hierarchy (Object) down to the actual class.
class Person {
protected final String name;
Person(String name) {
this.name = name;
System.out.println("Person(" + name + ")");
}
}
class Employee extends Person {
protected final double salary;
Employee(String name, double salary) {
super(name); // must be the first statement: the parent part is built first
this.salary = salary;
System.out.println("Employee(" + salary + ")");
}
}
class Manager extends Employee {
private final int teamSize;
Manager(String name, double salary, int teamSize) {
super(name, salary);
this.teamSize = teamSize;
System.out.println("Manager(" + teamSize + ")");
}
String card() { return name + " manages " + teamSize + " people, salary " + salary; }
}
public class Main {
public static void main(String[] args) {
Manager m = new Manager("Asha", 150000, 8);
System.out.println(m.card());
}
}
Person(Asha) Employee(150000.0) Manager(8) Asha manages 8 people, salary 150000.0
super.method() and super.field
Inside a subclass, super.method() calls the parent's version of a method – typically to extend its behaviour rather than replace it. super.field reaches a parent field hidden by a subclass field of the same name (avoid such hiding in real code).
class Account {
protected double balance;
protected String type = "ACCOUNT";
void deposit(double amt) { balance += amt; }
String describe() { return type + " balance " + balance; }
}
class SavingsAccount extends Account {
protected String type = "SAVINGS"; // hides the parent's field (legal, but confusing)
private double interestEarned;
@Override
void deposit(double amt) {
super.deposit(amt); // reuse the parent's logic ...
double bonus = amt >= 10000 ? amt * 0.01 : 0;
super.deposit(bonus); // ... and extend it
interestEarned += bonus;
}
@Override
String describe() {
return super.describe() + " (" + type + ", bonus " + interestEarned + ")"; // super.method() calls the parent version
}
String types() { return super.type + "/" + this.type; }
}
public class Main {
public static void main(String[] args) {
SavingsAccount s = new SavingsAccount();
s.deposit(5000);
s.deposit(20000);
System.out.println(s.describe());
System.out.println(s.types());
}
}
ACCOUNT balance 25200.0 (SAVINGS, bonus 200.0) ACCOUNT/SAVINGS
Types of inheritance
Java supports single (one parent), multilevel (a chain) and hierarchical (several children of one parent) inheritance. Multiple inheritance of classes is not allowed, and hybrid forms are possible only with interfaces.
// Single: Animal <- Dog
// Multilevel: Animal <- Dog <- Puppy
// Hierarchical: Animal <- Dog, Animal <- Cat
class Animal {
String eat() { return "eats"; }
}
class Dog extends Animal {
String bark() { return "barks"; }
}
class Puppy extends Dog {
String play() { return "plays"; }
}
class Cat extends Animal {
String meow() { return "meows"; }
}
public class Main {
public static void main(String[] args) {
Puppy p = new Puppy();
Cat c = new Cat();
System.out.println("Puppy: " + p.eat() + ", " + p.bark() + ", " + p.play()); // methods from all levels
System.out.println("Cat: " + c.eat() + ", " + c.meow());
System.out.println(p.getClass().getSuperclass().getSimpleName() + " " + Dog.class.getSuperclass().getSimpleName() + " " + Animal.class.getSuperclass().getSimpleName());
}
}
Puppy: eats, barks, plays Cat: eats, meows Dog Animal Object
// Why Java has no multiple inheritance of CLASSES – the "diamond problem":
class Printer { void start() { System.out.println("warming up"); } }
class Scanner { void start() { System.out.println("calibrating"); } }
// class AllInOne extends Printer, Scanner { } // ✘ not allowed: which start() would AllInOne inherit?
// Java allows a class to implement MANY interfaces instead (Interfaces topic).
// If two interfaces supply the same default method, the class must override it and choose:
interface CanPrint { default String start() { return "print"; } }
interface CanScan { default String start() { return "scan"; } }
class Office implements CanPrint, CanScan {
@Override public String start() { return CanPrint.super.start() + "+" + CanScan.super.start(); }
}
Upcasting, downcasting and instanceof
A subclass object can be stored in a superclass variable (upcasting, automatic). Only the superclass's members can then be called through that variable, though overridden methods still run the object's own version. Going back down needs an explicit cast, which throws ClassCastException if the object is not really of that type – so check with instanceof first (Java 16+ lets you bind a variable in the same step).
class Shape {
String name() { return "shape"; }
}
class Circle extends Shape {
final double r;
Circle(double r) { this.r = r; }
@Override String name() { return "circle"; }
double area() { return Math.PI * r * r; }
}
class Square extends Shape {
final double side;
Square(double side) { this.side = side; }
@Override String name() { return "square"; }
}
public class Main {
public static void main(String[] args) {
Shape s = new Circle(2); // upcasting: automatic and always safe
System.out.println(s.name()); // the object's own version runs
// s.area(); // does not compile: the variable's type is Shape
if (s instanceof Circle c) { // check, then downcast (pattern matching, Java 16+)
System.out.printf("area %.2f%n", c.area());
}
Shape other = new Square(3);
try {
Circle wrong = (Circle) other; // compiles, but the object is a Square
System.out.println(wrong.r);
} catch (ClassCastException e) {
System.out.println("ClassCastException: a Square is not a Circle");
}
}
}
circle area 12.57 ClassCastException: a Square is not a Circle
Composition vs inheritance
Use inheritance only for a true IS-A relationship where the subclass can be used anywhere the parent is expected. For HAS-A relationships, or to reuse code without exposing the parent's whole API, hold an object of the other class and delegate to it. "Favour composition over inheritance" is one of the best-known design guidelines.
import java.util.ArrayList;
import java.util.List;
// HAS-A: a Car has an Engine. Composition – the Car holds an Engine object and delegates to it.
class Engine {
private final int hp;
private boolean running;
Engine(int hp) { this.hp = hp; }
void start() { running = true; }
boolean isRunning() { return running; }
int hp() { return hp; }
}
class Car {
private final String model;
private final Engine engine; // composition
Car(String model, Engine engine) { this.model = model; this.engine = engine; }
String drive() {
engine.start(); // delegation
return model + " driving with " + engine.hp() + " hp, running=" + engine.isRunning();
}
}
// A classic misuse of inheritance: a Stack "IS-A" ArrayList would expose add(index), remove(index) …
// Composition exposes only what a stack should do.
class Stack<T> {
private final List<T> items = new ArrayList<>();
void push(T t) { items.add(t); }
T pop() { return items.remove(items.size() - 1); }
boolean isEmpty() { return items.isEmpty(); }
}
public class Main {
public static void main(String[] args) {
System.out.println(new Car("Nexon", new Engine(118)).drive());
Stack<String> st = new Stack<>();
st.push("a"); st.push("b"); st.push("c");
StringBuilder sb = new StringBuilder();
while (!st.isEmpty()) sb.append(st.pop());
System.out.println(sb);
}
}
Nexon driving with 118 hp, running=true cba
Common mistakes
- Parent without a no-arg constructor and a child constructor that does not call
super(...). - Expecting private fields to be accessible in the subclass.
- Trying to extend two classes, or a final class.
- Calling subclass-only methods through a superclass variable.
- Downcasting without instanceof – ClassCastException.
- Hiding fields by redeclaring them in the subclass.
- Inheriting just to reuse code when there is no real IS-A relationship.
Key points to remember
- class B extends A: B IS-A A and inherits A's accessible members.
- Constructors are not inherited; super(...) must be the first statement.
- Construction runs from the top of the hierarchy down.
- Single, multilevel and hierarchical inheritance; no multiple inheritance of classes.
- Every class extends Object directly or indirectly.
- Upcasting is automatic; downcasting needs a cast and instanceof.
Frequently asked questions
Why doesn't Java support multiple inheritance?
To avoid the ambiguity of the diamond problem and keep the language simple. Interfaces provide multiple inheritance of type (and, with default methods, of behaviour with explicit conflict resolution).
Are private members inherited?
They are part of the subclass object's memory, but they are not inherited as accessible members; the subclass reaches them only through the parent's accessible methods.
Can a subclass have a constructor with different parameters?
Yes; it just has to call some accessible superclass constructor.
Where can I learn more?
Read Java Inheritance and The super Keyword in Java, then practise with the exercises below.