Polymorphism, the Object Class, and is-a versus has-a

AP Computer Science A · Unit 3 — Class Creation

Two types, two jobs

In Employee e = new Manager("An", 8, 4); the variable has a declared type (Employee) and the object has an actual type (Manager). The compiler checks the declared type: e.bonus() fails to compile if bonus exists only in Manager. At run time Java uses the actual type to decide which body executes, so e.pay() runs the Manager version. That late decision is dynamic binding, and the ability of one line of code to run different bodies is polymorphism.

The payoff is an array or list of the superclass type holding mixed objects: one loop calling pay() makes every element behave according to its own class, and adding a new subclass later requires no change to the loop.

Everything extends Object

Every class inherits from Object, whose two methods matter here. The default toString() prints a class name and a hash code, which is useless, so classes override it; System.out.println(obj) calls toString() automatically. The default equals() compares references — true only when both variables point at the very same object — so a class that wants value comparison must override it. Note that == on objects always compares references and is never overridable.

is-a versus has-a

Use extends only for is-a (a Manager is an Employee). When one class merely contains another — a Library has Book objects — store it as an instance variable. That is composition, and it is the right answer far more often than inheritance.

Employee[] staff — same declared type ds[0] ds[1] ds[2] Employee Manager Intern superclass pay() overriding pay() overriding pay() for (Employee e : ds) tong += e.pay(); one line of code, three different method bodies — the REAL type decides
Where it is easy to get confused. All three top cells carry the declared type Employee, so the compiler only allows calls to what Employee has. But at run time, each cell jumps down into the method body of the real class beneath it. So the two questions must be kept separate: does this line compile is answered by the top row, while what gets printed is answered by the bottom row. Mixing the two questions into one is the source of most wrong answers in this chapter.

Worked example: comparing by value, and the == trap

A class Point has two integer coordinates. Override toString and write a method that compares by value. State what == and the comparison method give for two objects with the same coordinates.

Solution

public class Point {
    private int x;
    private int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() { return x; }
    public int getY() { return y; }

    public boolean sameAs(Point other) {
        return x == other.getX() && y == other.getY();
    }

    public String toString() {
        return "(" + x + ", " + y + ")";
    }
}

With Point p = new Point(2, 3); and Point q = new Point(2, 3);:

Note other.getX(): x is private, but private scope is by class, not by object, so writing other.x directly is also valid here. Using the accessor is still the safer habit when doing exam problems.

Common mistake

A deadly trap: using == to compare two objects and thinking you are comparing values. With String the trap is even nastier, because identical string literals usually share one memory region, so == happens to give true, while a string concatenated at run time gives false — the same line of code, two results. How to prevent it: set a hard rule for yourself, == only for numbers and boolean, and every object comparison calls equals. The second trap: calling a method that exists only in the subclass through a superclass-typed variable — that is a compile error, not a run-time error, even though the real object is indeed the subclass.

Key takeaway

The declared type decides what you are allowed to call, the real type decides which method body runs. println(obj) calls toString(). The default equals compares references; to compare values you must override it. And before typing extends, try reading it as the sentence X is a Y — if it does not sound right, what you need is an instance variable, not inheritance.

← Inheritance: extends, super, and Method Overriding · All AP Computer Science A lessons · Practice AP Computer Science A questions (free, instant scoring) · One-Dimensional Arrays and Traversals →