IAE Academy

FOR CORE AND IT JOBS · CHAPTER 3 OF 7

Inheritance

This chapter explains how a class extends another, the order constructors run in, how overriding picks a method at run time, and what equals, hashCode and toString promise. You need these to predict what Java code does, to use objects in hash collections, and to choose between extending and composing.

Updated 30 Oct 2026

What you will be able to do

You will predict what a chain of constructors prints, and which version of an overridden method runs. You will write equals, hashCode and toString that obey their contract. You will test whether a class should extend another or hold it as a field.

Before you start

  1. Chapter 2, Encapsulation and immutability

  2. Writing a class with fields, a constructor and methods, and creating objects with new

  3. Packages: grouping classes with a package statement

  4. Using ArrayList and HashSet from java.util (add, contains, size)

  5. Testing a reference with instanceof and casting it, as in (Point) o

  6. The remainder after whole-number division (a mod n)

Extending a class and chaining constructors

A subclass is a class declared with extends. Every object of it holds the fields of its superclass plus its own, so the superclass part must be built first. That is why constructors chain: each one first runs its parent's constructor, directly with super(...) or through this(...), a call to another constructor of its own class. A subclass can also override a method: supply a new body with the same signature (name and parameter types), labelled @Override so the compiler checks it. All code here is Java 17.

class Animal {
    Animal() { System.out.println("Animal built"); }
    String sound() { return "..."; }
}
class Dog extends Animal {
    Dog() { super(); System.out.println("Dog built"); }
    @Override String sound() { return "Woof"; }
}
public class Demo {
    public static void main(String[] args) {
        Animal a = new Dog();
        System.out.println(a.sound());
    }
}
// Animal built
// Dog built
// Woof

ORDER IN WHICH CONSTRUCTOR BODIES RUN

For each new Dog(), Dog() first calls Animal(), which calls Object(); the bodies then run left to right along the arrows, Object's first. super(...) or this(...) must be a constructor's first statement; with neither, the compiler inserts super(). If the parent has no no-argument constructor, call super(args) yourself or the code does not compile.

WHICH OVERRIDING METHOD RUNS

Holds for instance methods; static and private methods and fields are not overridden. An override needs the same signature, the same return type (or a subtype, for a reference type), access no narrower, and a parent method that is not final. In Animal a = new Dog(), the declared type Animal decides what you may call and the run-time class Dog picks the body, so a.sound() gives Woof. Inside Dog, super.sound() runs Animal's version.

protected (Chapter 2) opens a member to code in its own package and to subclasses anywhere. A subclass in another package has one limit: it may use the member on this or on a reference of its own type (or a subclass of it), not on a reference of the parent's type. So if Animal had a protected field name, then inside a Dog in another package name and otherDog.name compile, but someAnimal.name does not. Use protected sparingly: subclasses come to depend on it.

WATCH OUT FOR

A method with the same name but different parameters overloads; it does not override, and no error appears. Test: put @Override on it; a compile error means it is not an override.

WORKED EXAMPLE

Given class A { A() { System.out.println("A"); } }, class B extends A { B() { System.out.println("B"); } } and class C extends B { C() { System.out.println("C"); } }, what does new C() print?

Solution
  1. C() has no explicit first statement, so the compiler inserts super(), which calls B(): the parent must be built before C's body runs.

  2. B() and A() likewise start with an inserted super(). A()'s super() calls Object(), which prints nothing and returns.

  3. Now bodies run from the top down: A's body prints A, then control returns to B, whose body prints B, then to C, whose body prints C.

Answer: A, then B, then C, each on its own line.

The Object class and its contract

Every class except Object extends it, directly or through its ancestors, so every object has equals, hashCode and toString. The defaults are weak: equals compares references (like ==), hashCode is tied to the object's identity, not its values, and toString gives the class name, @ and the hash code in hex. To compare objects by value, override all three.

WHAT EQUALS PROMISES

For all non-null x, y, z. Lines 1 to 3 make equals reflexive (an object equals itself), symmetric (order does not matter) and transitive (equality passes along a chain). Repeated calls must give the same answer while the compared fields are unchanged.

WHAT HASHCODE PROMISES

For all non-null x, y. The reverse is not required: unequal objects may share a hash code. Repeated calls must return the same value while those fields are unchanged. If you override equals, override hashCode too, using only fields that equals compares.

WHY THE PROMISE IS NEEDED

A simplified model of a new HashSet<>(): n buckets (a power of 2; 16 at first), int hash code h, bucket 0 to n − 1. Java first mixes the high bits of h into the low ones, which changes nothing while 0 ≤ h < 65,536. The set searches one bucket and calls equals only on entries with the same h, so equal objects with different h are never found.

final class Point {
    private final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point)) return false;
        Point p = (Point) o;
        return x == p.x && y == p.y;
    }
    @Override public int hashCode() { return 31 * x + y; }
    @Override public String toString() { return "Point(" + x + "," + y + ")"; }
}
public class PointDemo {
    public static void main(String[] args) {
        Point p = new Point(3, 4), q = new Point(3, 4);
        System.out.println(p + " " + p.equals(q) + " " + (p == q));
    }
}
// Point(3,4) true false

The parameter must be Object. o instanceof Point is true when o refers to a Point and false for null, so null is covered. The cast (Point) o then lets you read p.x and p.y. Joining a string with + calls toString. The class is final: a subclass that added a colour field and compared it in its own equals would break symmetry, since a Point could equal a coloured point that does not equal it back.

WATCH OUT FOR

Changing a field that hashCode uses after the object is in a HashSet strands it in the wrong bucket. Test: is the field in hashCode? Then make it final.

WORKED EXAMPLE

Point(3, 4) is added to a HashSet with n = 16 buckets. Then another Point(3, 4) is added. Using the Point class above, what are the hash code and the bucket, and how large is the set?

Solution
  1. Hash code: 31 × 3 + 4 = 97 for the first point, and the same for the second, because the fields are equal.

  2. Bucket: 97 mod 16 = 1, since 16 × 6 = 96 leaves remainder 1. 97 is below 65,536, so the mixing step changes nothing. Both points go to bucket 1.

  3. In bucket 1 the set finds an entry with the same hash code 97, so it calls equals. Same class, 3 = 3 and 4 = 4, so it returns true and the second point is not stored.

  4. Without the hashCode override, the two identity-based hash codes would almost always differ, so the set would almost always skip equals and store both, although equals says they are equal.

Answer: Hash code 97, bucket 1, and the set holds 1 element.

Is-a, has-a and when inheritance goes wrong

Extending says more than "reuse this code". It says every object of the subclass can be used wherever the parent is expected, so any caller written against the parent must keep working. That is the is-a test, and it is about behaviour, not about nouns in everyday speech.

THE SUBSTITUTION TEST

T is the parent class, S the subclass, x an object. A promise of T is anything T's methods guarantee a caller about results or state, such as "after setWidth(w), the height is unchanged"; P is any statement that follows from those promises. One failing P is enough to reject the extension.

class Rectangle {
    protected int w, h;
    Rectangle(int w, int h) { this.w = w; this.h = h; }
    void setWidth(int w) { this.w = w; }
    int area() { return w * h; }
}
class Square extends Rectangle {
    Square(int s) { super(s, s); }
    @Override void setWidth(int w) { this.w = w; this.h = w; }
}
public class Shapes {
    public static void main(String[] args) {
        Rectangle r = new Square(3);
        r.setWidth(5);
        System.out.println(r.area());
    }
}
// 25

A caller who sees a Rectangle expects 5 × 3 = 15. A square is a rectangle in geometry, yet this Square fails the test: it breaks the promise that setWidth leaves the height alone.

The usual better choice is composition: the new class holds the other as a private field and exposes only the methods it wants. A Square could hold a private Rectangle built as new Rectangle(s, s) and offer only area(), which calls the field's area(). setWidth is then not part of Square, so no promise breaks. Extend only when the substitution test passes and you want every parent method on your class.

WORKED EXAMPLE

Engine has methods start() and isRunning(), and promises: after start(), isRunning() returns true. Someone writes class Car extends Engine with a fuel field in litres, and overrides start() so that it does nothing when fuel is 0 litres and calls super.start() otherwise. Apply the substitution test and say what to write instead.

Solution
  1. Take P from Engine's promise: after start(), isRunning() returns true. Any caller written against Engine may rely on it.

  2. Take a Car x whose fuel is 0 litres. x.start() does nothing, so x.isRunning() stays false. P fails for x, and one failing P rejects the extension.

  3. Write a field instead: a private final Engine engine in Car, set in Car's constructor, and a start() in Car that checks fuel > 0 and then calls engine.start(). A Car is no longer accepted where an Engine is expected, so no Engine caller is surprised.

Answer: Do not extend. Use composition: Car holds a private Engine, and its start() checks the fuel before calling engine.start().

Check yourself

CHECK YOURSELF 1

class Animal has only one constructor, Animal(String name). class Dog extends Animal has a constructor Dog() { System.out.println("Dog"); } with no explicit super call. What happens?

  1. (A)

    It prints Dog; name is set to null

  2. (B)

    It does not compile

  3. (C)

    It compiles and throws an exception when Dog is created

  4. (D)

    It prints Dog; the compiler passes an empty string

Answer and solution

Answer: (B)

  1. The compiler inserts super() as the first statement of Dog().

  2. Animal has no no-argument constructor, so that call cannot be resolved.

  3. The failure is at compile time. Fix: call super("x") explicitly.

CHECK YOURSELF 2One or more options are correct

Which statements about equals and hashCode are correct?

  1. (A)

    If x.equals(y) is true, x and y must have the same hash code

  2. (B)

    If x and y have the same hash code, x.equals(y) must be true

  3. (C)

    x.equals(null) must return false for a non-null x

  4. (D)

    public boolean equals(Point p) in class Point overrides Object.equals

Answer and solution

Answer: (A), (C)

  1. A is the hashCode promise.

  2. B is the reverse, which is not required: different objects can share a hash code.

  3. C is part of the equals promise.

  4. D has parameter type Point, not Object, so it overloads. @Override would fail to compile.

CHECK YOURSELF 3

Point uses hashCode() = 31 * x + y. A HashSet has 16 buckets and chooses the bucket as hash mod 16. What is the bucket index of Point(2, 6)?

Answer and solution

Answer:

  1. Hash code: 31 × 2 + 6 = 68.

  2. 68 mod 16: 16 × 4 = 64, remainder 4.

CHECK YOURSELF 4

A Library class must keep Book objects and let callers do only two things: add a book and count the books. Which design fits?

  1. (A)

    class Library extends ArrayList<Book>

  2. (B)

    class Library with a private ArrayList<Book> field and public add and count methods

  3. (C)

    class Library extends Book

  4. (D)

    class Book extends Library

Answer and solution

Answer: (B)

  1. A makes every list method, such as remove, clear and set, part of Library, so callers could do far more than add and count.

  2. C and D fail the is-a test: a Library is not a Book, and a Book is not a Library.

  3. B holds the list as a private field (composition) and exposes exactly add and count.