Lesson 24 of 34 · Inheritance & Interfaces
Java Inheritance: extends and super
Classes in real programs are often variations of each other: a car, a bike and a truck are all vehicles. Copy-pasting the shared fields and methods into every class works until you need to change them — then you have to fix the same bug three times.
Inheritance lets one class build on another. The new class automatically gets the fields and methods of the existing one and only adds what is different.
extends: the "is-a" relationship
class Animal {
protected String name;
Animal(String name) {
this.name = name;
}
String describe() {
return name + " is an animal";
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
String fetch() {
return name + " fetches the stick!";
}
}
Dog extends Animal means a Dog is an Animal. Animal is the superclass (parent), Dog the subclass (child). A Dog object has everything an Animal has, plus its own fetch() method:
Dog rex = new Dog("Rex");
System.out.println(rex.describe()); // inherited from Animal
System.out.println(rex.fetch()); // defined in Dog
Rex is an animal
Rex fetches the stick!
super(...) calls the parent constructor
Constructors are not inherited. Every subclass constructor must first let the parent set up its part of the object by calling super(...) with arguments for one of the parent's constructors. The parent constructor runs first, then the subclass continues:
class Hero {
protected String name;
protected int hp;
Hero(String name, int hp) {
this.name = name;
this.hp = hp;
System.out.println("Hero " + name + " created");
}
}
class Knight extends Hero {
protected int armor;
Knight(String name, int armor) {
super(name, 120); // every knight starts with 120 hp
this.armor = armor; // then the Knight's own field
System.out.println("Knight ready, armor " + armor);
}
}
new Knight("Lancel", 30) prints:
Hero Lancel created
Knight ready, armor 30
Notice that Knight passes a fixed value (120) up to the parent — callers never choose a knight's starting health.
If you leave the call out, Java silently inserts super(), which only compiles when the parent has a constructor without parameters. Traditionally super(...) had to be the very first statement; since Java 25 you may run simple checks before it (such as validating an argument) as long as they don't use the object under construction. Calling super(...) first is still the usual style.
protected, private and the Object class
A subclass inherits private fields too, but it cannot touch them directly: name has private access in Animal. Mark fields protected when subclasses should use them, or keep them private and give the parent getters.
If a class doesn't say extends, it extends Object, the root of every Java class. That is why every object has toString(), equals() and hashCode() — they are inherited from Object.
One parent only — and only for "is-a"
A Java class can extend exactly one class; class C extends A, B does not compile. (Interfaces, later in this chapter, are how a class takes on several roles.)
Use inheritance only when the subclass truly is a kind of the parent. A car has an engine — that is a field (private Engine engine;), called composition, not class Car extends Engine.
Common mistakes
- Forgetting
super(...)when the parent has no parameterless constructor: constructor Vehicle in class Vehicle cannot be applied to given types. - Reaching for private parent fields: use
protectedor a getter. - Re-declaring inherited fields in the subclass (
protected String name;again). That creates a second, separate field that hides the parent's one — a classic source of confusing bugs. - Inheriting for code reuse alone: if "X is a Y" sounds wrong, use a field instead.
Assignment
Vehicle is finished. Complete its three subclasses and one static method:
Car(String name)— a car has 4 wheels. Addhonk(), which returns"<name> says: beep beep!".Bike(String name)— a bike has 2 wheels. AddringBell(), which returns"<name> says: ring ring!".Truck(String name, int cargoTons)— a truck has 6 wheels and remembers its cargo. AddcargoInfo(), which returns"<name> carries <cargoTons> tons".Main.totalWheels(Vehicle[] fleet)— the total number of wheels of all vehicles in the array (0for an empty array).
new Car("Rover").describe() // "Rover has 4 wheels" (inherited method)
new Truck("Atlas", 12).cargoInfo() // "Atlas carries 12 tons"Premium lesson
Unlock the full Learn Java course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Inheritance in other languages
- JavaScript Inheritance: extends, super and static · JavaScript
- Python Inheritance and super() · Python
- Go Struct Embedding and Composition · Go
- C# Inheritance: virtual, override and base · C#
Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.
Lesson last updated on .