Jack Ng

Essay

Learning Java, Part 7: Inheritance and Polymorphism

Study notes on extends, member access across a hierarchy, super for constructors and members, constructor order, superclass references, overriding and dynamic dispatch, abstract classes, final, and the Object class with equals, hashCode and toString. Written entirely by an AI model.

Inheritance lets one class build on another. It is the topic most likely to appear as a long exam question in CITS2005, usually as “explain overriding with a short example” or “what does this hierarchy print?”.

extends

A subclass extends a superclass and inherits its fields and methods. It then adds or changes only what is different.

class Shape {
    String name;
    Shape(String name) { this.name = name; }
    double area() { return 0; }
    String describe() { return name + " with area " + area(); }
}

class Rectangle extends Shape {
    double w, h;
    Rectangle(double w, double h) {
        super("rectangle");       // run Shape's constructor first
        this.w = w;
        this.h = h;
    }
    @Override
    double area() { return w * h; }
}

class Square extends Rectangle {
    Square(double side) {
        super(side, side);
        name = "square";
    }
}

public class Shapes {
    public static void main(String[] args) {
        System.out.println(new Rectangle(2, 3).describe());
        System.out.println(new Square(4).describe());
    }
}
rectangle with area 6.0
square with area 16.0
  • Java allows single inheritance of classes: a class extends exactly one other. (Interfaces, in Part 8, give a form of multiple inheritance.) Python allows several base classes.
  • A chain like Shape → Rectangle → Square is a multilevel hierarchy. Square inherits everything from both.
  • Inheritance should model is-a: a square is a rectangle. If the relationship is “has-a” (a car has an engine), use a field instead. This is called composition, and CITS4401 will push you to prefer it.

Member access across a hierarchy

A subclass inherits private members but cannot access them directly. It must go through the superclass’s public or protected methods. protected members are visible to subclasses, even in other packages. A common design keeps fields private and gives subclasses a protected getter.

super

super has two uses:

  1. super(args) calls the superclass constructor. If you use it, it must be the first statement in the constructor. If you don’t, Java inserts super() with no arguments, which fails to compile when the superclass has no no-argument constructor. That error message (“constructor Shape in class Shape cannot be applied to given types”) is a frequent surprise.
  2. super.member reaches the superclass version of a method or field that the subclass has overridden or hidden.

Constructor order

Constructors run from the top of the hierarchy down:

class A { A() { System.out.println("A"); } }
class B extends A { B() { System.out.println("B"); } }
class C extends B { C() { System.out.println("C"); } }

public class Order {
    public static void main(String[] args) {
        new C();
    }
}
A
B
C

A superclass must be fully set up before a subclass can rely on it.

Superclass references and subclass objects

A variable of a superclass type can refer to an object of any of its subclasses. The variable’s type decides which members you may call; the object’s type decides which version runs.

class Animal {
    String sound() { return "..."; }
}
class Dog extends Animal {
    @Override String sound() { return "woof"; }
    void fetch() { System.out.println("fetching"); }
}
class Cat extends Animal {
    @Override String sound() { return "meow"; }
}

public class Zoo {
    public static void main(String[] args) {
        Animal[] pets = { new Dog(), new Cat(), new Animal() };
        for (Animal a : pets) System.out.println(a.sound());

        Animal a = new Dog();
        // a.fetch();          // compile error: Animal has no fetch()
        if (a instanceof Dog d) d.fetch();   // check, then cast
    }
}
woof
meow
...
fetching

This is polymorphism: one loop, three behaviours. The choice of method is made at runtime from the actual object, which is called dynamic method dispatch.

To call a subclass-only method, cast down after checking with instanceof. A wrong cast throws ClassCastException. The form a instanceof Dog d, which checks and names the cast in one step, has been standard since Java 16. The book’s older form is if (a instanceof Dog) ((Dog) a).fetch();.

Overriding versus overloading

Overriding Overloading
Where subclass redefines a superclass method same class (or subclass) adds a method
Signature same name and same parameters same name, different parameters
Chosen at runtime, by object type at compile time, by argument types

Rules for overriding:

  • The return type must be the same, or a subtype (“covariant return”).
  • Access cannot be narrowed: a public method cannot be overridden as private.
  • It cannot throw broader checked exceptions (Part 9).
  • static methods are not overridden; a subclass static method with the same signature only hides the original.
  • Fields are not polymorphic. A field in a subclass with the same name hides the superclass field, and which one you get depends on the variable’s type. Avoid it.

Always write @Override. If you misspell the name or get a parameter type wrong, the compiler then reports an error instead of silently creating an overload.

public class Exam {
    static class Base {
        void hello() { System.out.println("Base.hello"); }
        void greet() { hello(); }               // dispatch happens here
    }
    static class Derived extends Base {
        @Override void hello() {
            super.hello();
            System.out.println("Derived.hello");
        }
    }
    public static void main(String[] args) {
        Base b = new Derived();
        b.greet();
    }
}
Base.hello
Derived.hello

Even though greet is defined in Base, its call to hello() runs the Derived version, because this is a Derived.

Abstract classes

An abstract class cannot be instantiated. It can declare abstract methods, with no body, that every concrete subclass must implement. Use it when a superclass has no sensible default for a method:

abstract class Drink {
    private final String name;
    Drink(String name) { this.name = name; }
    abstract int priceCents();                  // no body
    String label() {                            // concrete method using it
        return name + " $" + priceCents() / 100.0;
    }
}
class Latte extends Drink {
    Latte() { super("latte"); }
    @Override int priceCents() { return 550; }
}

public class Cafe {
    public static void main(String[] args) {
        Drink d = new Latte();
        System.out.println(d.label());
        // new Drink("x");    // compile error: Drink is abstract
    }
}
latte $5.5

A class with any abstract method must itself be declared abstract. An abstract class may still have fields, constructors and concrete methods. That is the main difference from an interface.

final

  • A final method cannot be overridden.
  • A final class cannot be extended. String is final.
  • A final variable can be assigned only once. For a reference, that fixes which object it points at, not the object’s contents: a final int[] can still have its elements changed.

The Object class

Every class extends Object, directly or indirectly. Its most important methods:

Method Default behaviour Override when
toString() class name and hash, Point@1b6d3586 always, for readable output
equals(Object o) same as == objects with the same contents should count as equal
hashCode() based on identity whenever you override equals
getClass() the runtime class (final; not overridable)

If two objects are equals, they must have the same hashCode; otherwise HashMap and HashSet (Part 13) break. A correct pair:

import java.util.Objects;

class Coin {
    private final String currency;
    private final int cents;
    Coin(String currency, int cents) { this.currency = currency; this.cents = cents; }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Coin other)) return false;
        return cents == other.cents && currency.equals(other.currency);
    }
    @Override
    public int hashCode() { return Objects.hash(currency, cents); }
    @Override
    public String toString() { return cents + " " + currency; }
}

public class Coins {
    public static void main(String[] args) {
        Coin a = new Coin("AUD", 50), b = new Coin("AUD", 50);
        System.out.println(a == b);
        System.out.println(a.equals(b));
        System.out.println(a.hashCode() == b.hashCode());
        System.out.println(a);
    }
}
false
true
true
50 AUD

Note the parameter type is Object. Writing equals(Coin o) creates an overload, not an override, and collections ignore it. @Override catches that mistake.

Modern Java. A record (Java 16) writes the fields, constructor, accessors, equals, hashCode and toString for you: record Coin(String currency, int cents) {}. Sealed classes (Java 17) list exactly which subclasses are allowed.

Exam-style checks

  • Explain inheritance and method overriding with a code example of ten lines or fewer.
  • What is printed when a superclass method calls a method the subclass overrides?
  • Why must super(...) come first in a constructor? What happens if you leave it out?
  • What is the difference between an abstract class and a concrete class? When would you use one?
  • Why must hashCode be overridden together with equals?

Where to practise

Schildt’s Chapter 7 builds a TwoDShape hierarchy with triangles and rectangles, then makes area() abstract. Build your own: an abstract Employee with pay(), and Salaried and Hourly subclasses. Put them in an Employee[], total the payroll in one loop, and give each class toString, equals and hashCode.