Inheritance

Inheritance is the is-a relation of lesson 045 written as extends. A subclass gets the fields and methods of its superclass, may add its own, and may replace a method it inherited. The constructor of the superclass still runs for every object of the subclass, which is the part that surprises a beginner.

extends

class Dog extends Animal makes Dog a subclass of Animal. A dog object has the name field and the name() method of the animal, and it can be used wherever an animal is expected, which is the subject of the next lesson.

The file Animal.java:

public class Animal { private final String name; Animal(String name) { this.name = name; } String name() { return name; } String speak() { return name + " makes a sound"; } public static void main(String[] args) { Animal animal = new Animal("animal"); Dog dog = new Dog("Rex"); Cat cat = new Cat("Mia"); System.out.println(animal.speak()); System.out.println(dog.speak()); System.out.println(cat.speak()); } } class Dog extends Animal { Dog(String name) { super(name); } @Override String speak() { return name() + " barks"; } } class Cat extends Animal { Cat(String name) { super(name); } @Override String speak() { return name() + " meows"; } }

javac -Xlint:all Animal.java
java Animal

animal makes a sound
Rex barks
Mia meows

The subclass reads the name through name(), because the field is private to Animal: a subclass inherits the members but not the access to a private field. A protected field would be visible, and private plus a getter is the safer habit.

super

super(name) calls the constructor of the superclass, and super.speak() calls the inherited method from inside an override. The constructor call must be the first statement of the subclass constructor, because the superclass part of the object is built before the subclass part.

A subclass constructor with no explicit super(...) gets an implicit super(), which requires a no-argument constructor in the superclass. If the superclass has only a constructor with parameters, every subclass constructor must call it explicitly, and a call without it is a compile error.

Overriding

An override has the same name, the same parameter list and a compatible return type. @Override is optional and strongly recommended: it makes the compiler check that a method really overrides something, so a typo in the name is an error rather than a new method that nothing calls.

A subclass may not reduce the visibility of an overridden method: a public method cannot become private or package-private in the subclass. It may add final to stop further overrides, which lesson 054 takes.

The constructor chain

Every creation of a subclass object runs the superclass constructor first. The program below prints one line from each, in that order:

public class Chain { public static void main(String[] args) { new Child(); } } class Parent { Parent() { System.out.println("parent"); } } class Child extends Parent { Child() { System.out.println("child"); } }

javac -Xlint:all Chain.java
java Chain

parent
child

The order matters for a subclass that reads state the superclass constructor sets. A common bug is to call an overridden method from the superclass constructor: the subclass method runs before the subclass fields are initialised, and it sees their default values.

Exercises

  1. Add a Bird class that extends Animal and overrides speak.
  2. Give Animal a second constructor with a sound and use super(name, sound) from Dog.
  3. Remove @Override from Dog and misspell the method name. What does the compiler do, and what happens with the annotation?
  4. Print the class of a dog with getClass().getSimpleName().

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does extends declare?

    Answer

    The is-a relation between a subclass and its superclass

    A subclass is a kind of its superclass, and it inherits the fields and methods.

  2. What must be the first statement of a subclass constructor?

    Answer

    A call to super(...) or this(...)

    The superclass part of the object is built before the subclass part.

  3. What does @Override make the compiler check?

    Answer

    That the method really overrides a superclass method

    The annotation catches a misspelled or wrongly typed override at compile time.

  4. What does this program print? public class Q1 { public static void main(String[] args) { Animal a = new Animal(); System.out.println(a.speak()); } } class Animal { String speak() { return "sound"; } }

    Answer

    sound

    The base class method returns the word sound.

  5. What does this program print? public class Q2 { public static void main(String[] args) { Dog dog = new Dog(); System.out.println(dog.speak()); } } class Animal { String speak() { return "sound"; } } class Dog extends Animal { @Override String speak() { return "woof"; } }

    Answer

    woof

    The subclass override replaces the inherited method for a dog object.

  6. What does this program print? public class Q3 { public static void main(String[] args) { new Child(); } } class Parent { Parent() { System.out.println("p"); } } class Child extends Parent { Child() { System.out.println("c"); } }

    Answer

    p / c

    The superclass constructor runs before the subclass constructor body.

  7. What does this program print? public class Q4 { public static void main(String[] args) { Dog dog = new Dog("Rex"); System.out.println(dog.name); } } class Animal { String name; Animal(String name) { this.name = name; } } class Dog extends Animal { Dog(String name) { super(name); } }

    Answer

    Rex

    The subclass constructor passes the name to super, which stores it in the inherited field.

  8. Can a subclass read a private field of its superclass directly?

    Answer

    No, it needs a getter or a protected field

    A private member is visible only inside its own class, subclasses included as outside.

  9. What does this program print? public class Q5 { public static void main(String[] args) { Animal a = new Dog(); System.out.println(a.speak()); } } class Animal { String speak() { return "sound"; } } class Dog extends Animal { @Override String speak() { return "woof"; } }

    Answer

    woof

    The object is a dog, so the overridden method runs even through a supertype reference.

  10. What does super.speak() do inside an override?

    Answer

    Calls the superclass version of the method

    super selects the inherited implementation instead of the override.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev