OOP: Inheritance, Polymorphism, Interfaces and Inner Classes

Which method runs and what compiles: the base for most other topics.

8 lessons · 23 past questions · 111 marks in the papers collected here

Open the interactive lessons →OOP: Inheritance, Polymorphism, Interfaces and Inner Classes past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Constructors and super
  2. Override or overload?
  3. Dynamic dispatch
  4. final and private
  5. toString and equals
  6. Static type, casts and instanceof
  7. Abstract classes and interfaces
  8. Callbacks and private inner classes

1. Constructors and super

One new can run several constructors on one object.

the order in which an object of a subclass is built

A VipTicket is a kind of Ticket. It has the seat that every ticket has, plus a lounge number of its own. When you write new VipTicket(2), someone has to fill both fields. Which code does which part, and in what order?

Think of a house: the ground floor is built before the first floor, because the upper floor rests on it. Here the ground floor is the parent class. The analogy stops at one point: you still get one house, so one object, never a separate parent object.

Why this order? The child's code is allowed to use what the parent provides. That is only safe if the parent part is ready first. So Java makes the first line of every constructor hand control upwards: either super(...) (a constructor of the parent) or this(...) (another constructor of the same class, which in turn goes upwards).

The first-line rule

On this JDK, this(...) or super(...) must be the first statement of a constructor. If you write neither, the compiler inserts super();, the parent's constructor with no arguments.

Here is the whole program. Read it once, then step through the picture.

Three constructors

class Ticket {
    String seat;
    Ticket() {
        this("open");
        System.out.println("Ticket()");
    }
    Ticket(String s) {
        seat = s;
        System.out.println("Ticket(String) " + s);
    }
}
class VipTicket extends Ticket {
    int lounge;
    VipTicket(int n) {
        super();
        lounge = n;
        System.out.println("VipTicket(int) " + n);
    }
}
public class Main {
    public static void main(String[] args) {
        VipTicket t = new VipTicket(2);
        System.out.println(t.seat + " / " + t.lounge);
    }
}

One object, three constructors

  1. new makes one object with default field values, then enters VipTicket(int).
  2. The first line, super(), pauses this body and enters the parent constructor.
  3. this("open") hands over to another constructor of the same class. Still one object.
  4. The deepest constructor finishes first: it fills seat and prints.
  5. Control returns to Ticket(), which prints its own line.
  6. Only now does the child body run: it sets lounge and prints last.
  7. new hands back one reference, and main stores it in t.

Worked example: The line you did not write

Problem.

What does this program print?

class Lamp {
    Lamp() { System.out.println("base ready"); }
}
class DeskLamp extends Lamp {
    DeskLamp() { System.out.println("arm ready"); }
}
public class Main {
    public static void main(String[] args) {
        new DeskLamp();
    }
}

What is asked.

The printed lines, in order.

Idea.

Add the hidden super(); and then run from the top.

  1. new DeskLamp() enters DeskLamp().
  2. DeskLamp() writes no first-line call, so the compiler has inserted super();.
  3. Lamp() runs and prints base ready.
  4. Control returns, and DeskLamp() prints arm ready.

Answer.

base ready, then arm ready

Common mistake.

Thinking only the constructor named after new runs.

What if

The Lamp program prints base ready and then arm ready.

  • Lamp gets only a constructor with a parameter: Lamp(int w) { } replaces Lamp(). What happens to DeskLamp?
    It no longer compiles.. The inserted super(); looks for a parent constructor with no arguments, and there is none.
  • DeskLamp() becomes this(3); followed by its print, and DeskLamp(int h) { System.out.println("height " + h); } is added. What prints?
    It prints base ready, height 3, arm ready.. this(3) goes sideways first; the sideways constructor still gets the inserted super();. The parent runs once.
  • Lamp() is marked private. Does the program compile?
    It does not compile.. The child must call a parent constructor, and a private one is invisible to it.

Worked example: A private field in the parent

Problem.

FruitCrate must label itself. The field label is private in Crate. What prints?

class Crate {
    private String label;
    Crate(String label) { this.label = label; }
    String label() { return label; }
}
class FruitCrate extends Crate {
    int kg;
    FruitCrate(String fruit, int kg) {
        super(fruit + "-box");
        this.kg = kg;
    }
}
public class Main {
    public static void main(String[] args) {
        FruitCrate f = new FruitCrate("mango", 12);
        System.out.println(f.label() + " " + f.kg);
    }
}

What is asked.

The printed line.

Idea.

A child sets a parent's private field only by passing a value to the parent's constructor.

  1. FruitCrate("mango", 12) first calls super("mango-box").
  2. Crate stores that text in its private label.
  3. Back in the child, this.kg = kg; stores 12.
  4. label() is an inherited method, so it can read the private field for us.

Answer.

mango-box 12

Common mistake.

Writing label = fruit; in the child. The child cannot see a private field, so that line is rejected.

Sideways or upwards

this(...)

Calls another constructor of the same class.

Box() { this(10); }
Box(int s) { size = s; }

super(...)

Calls a constructor of the parent class.

Box() { super(10); }

The difference. The first word of the first line.

this(...) reuses your own class; super(...) builds the inherited part. A constructor can start with only one of them.

When this breaks

"The parent is fully built first" does not mean a parent constructor only runs parent code. If it calls a method that the child overrides, the child's body runs while the child's fields still hold their defaults.

The early call

class Frame {
    Frame() { System.out.println("size seen: " + size()); }
    int size() { return 1; }
}
class Poster extends Frame {
    private int width = 40;
    @Override
    int size() { return width; }
}
public class Main {
    public static void main(String[] args) {
        Poster p = new Poster();
        System.out.println("size now: " + p.size());
    }
}

2. Override or overload?

Two methods can share a name for two very different reasons.

how Java chooses among methods that share a name

A Tuba is a Horn. The parent can blow a number of times, blow(int), or blow a tune, blow(String). The tuba wants its own sound for one of the two. What happens to the other one, and how does Java know which you meant? The parent also has practice(), which calls blow(2). A call written like that inside a parent method is a call on the object itself, so a child's override answers it; the next lesson shows why.

Think of a form with a name and a number of blanks. "blow, one number blank" and "blow, one text blank" are different forms, even with the same title. A child can rewrite the answer to one form and leave the other untouched. The analogy stops at types: two forms can differ only in what kind of thing goes into a blank.

Why two mechanisms? The compiler must know, before the program runs, that some method accepts your arguments. So it chooses the signature from what is written. The object's class is unknown at that time, so the choice of body for that signature is left until the program runs.

Two steps for every call

StepWhenUses
1. pick the signaturecompile timetype of the variable and of each argument, as written
2. pick the bodyrun timeclass of the object

Worked example: One override, one untouched

Problem.

What does this print?

class Horn {
    String blow(int times) { return "toot x" + times; }
    String blow(String tune) { return "toot " + tune; }
    String practice() { return blow(2); }
}
class Tuba extends Horn {
    @Override
    String blow(int times) { return "oompah x" + times; }
}
public class Main {
    public static void main(String[] args) {
        Horn h = new Tuba();
        System.out.println(h.practice());
        System.out.println(h.blow("march"));
    }
}

What is asked.

Both lines.

Idea.

For each call, fix the signature first, then ask the object.

  1. h.practice() is not overridden, so the body in Horn runs and calls blow(2) on this object.
  2. The argument 2 is an int, so the signature is blow(int). Tuba overrides it and returns oompah x2.
  3. h.blow("march") fixes the signature blow(String).
  4. Tuba has no blow(String), so the inherited body returns toot march.

Answer.

oompah x2, then toot march

Common mistake.

Believing that overriding one blow replaces both.

What if

The Horn program prints oompah x2 and toot march.

  • The tuba's method becomes String blow(long times) and @Override is removed. What prints for the first call?
    It prints toot x2.. blow(long) is a new overload. The call blow(2) written in Horn fixes blow(int), which nobody overrides now.
  • Same change, but @Override stays. Compile or not?
    It does not compile.. @Override asks the compiler to confirm that a parent method is really being replaced. It is not.
  • The tuba's blow(int) returns int instead of String. Compile or not?
    It does not compile.. The signature matches, so it is an override, and an override cannot swap the return type for an unrelated one.

Worked example: The written type of an argument

Problem.

The same text is passed twice. Does it land in the same bin?

class Sorter {
    String take(Object o) { return "object bin"; }
    String take(String s) { return "text bin"; }
}
public class Main {
    public static void main(String[] args) {
        Sorter s = new Sorter();
        Object x = "pen";
        System.out.println(s.take(x));
        System.out.println(s.take("pen"));
    }
}

What is asked.

Both lines.

Idea.

Overloads are chosen from the argument's written type, never from the object.

  1. x is written as Object, although it holds a String.
  2. For s.take(x) only take(Object) accepts an Object.
  3. The literal "pen" is written as a String, so both overloads accept it.
  4. Of two that fit, Java takes the more specific one, take(String).

Answer.

object bin, then text bin

Common mistake.

Expecting Java to look inside x at run time.

One type in the parameter list

Override

class Kid extends Dad {
    void hum(String tune) { }
}

Overload

class Kid extends Dad {
    void hum(Object tune) { }
}

The difference. String against Object, with Dad declaring hum(String).

Same signature replaces; a different parameter list adds a second method.

When this breaks

"The child's version wins" fails for a method the child only adds. Through a parent-typed variable the compiler never sees the added overload, even when it fits better.

Worked example: Same object, two answers

Problem.

Both variables hold a KitchenScale. Do both calls print the same?

class Scale {
    String read(long grams) { return "base long"; }
}
class KitchenScale extends Scale {
    @Override
    String read(long grams) { return "kitchen long"; }
    String read(int grams) { return "kitchen int"; }
}
public class Main {
    public static void main(String[] args) {
        Scale a = new KitchenScale();
        KitchenScale b = new KitchenScale();
        System.out.println(a.read(5));
        System.out.println(b.read(5));
    }
}

What is asked.

Both lines.

Idea.

The variable's type limits which signatures can be chosen.

  1. For a.read(5) the compiler searches Scale, which has only read(long). The int 5 is converted to the wider type long.
  2. At run time KitchenScale overrides read(long), so the first line is kitchen long.
  3. For b.read(5) the compiler searches KitchenScale and finds read(int), an exact fit.
  4. That body prints kitchen int.

Answer.

kitchen long, then kitchen int

Common mistake.

Assuming the object alone decides.

3. Dynamic dispatch

The object answers method calls, whatever the variable is called.

which body runs when a parent-typed variable holds a child object

A café menu lists "drink: serve". The barista behind the counter holds whatever was actually made, perhaps a latte. When you ask for "serve", you get the latte's way of serving, although the menu only said "drink".

In code: Drink d = new Latte();. The left side is the menu entry, the static type. The right side is the thing made, the runtime class. Storing a child in a parent variable is an upcast; it changes nothing inside the object. The café analogy stops at fields, as you will see.

Why ask the object? Code written for Drink must keep working for drinks invented later. If the variable's type chose the body, a new subclass could never change how old code behaves. So Java checks the name early and chooses the body late.

Worked example: Call through the parent

Problem.

What does this print?

class Drink {
    String kind = "plain";
    static String shelf() { return "drink shelf"; }
    String serve() { return "pour"; }
    String order() { return "order: " + serve(); }
}
class Latte extends Drink {
    String kind = "latte";
    static String shelf() { return "coffee shelf"; }
    @Override
    String serve() { return "steam, pour"; }
    String art() { return "heart"; }
}
public class Main {
    public static void main(String[] args) {
        Drink d = new Latte();
        System.out.println(d.serve());
        System.out.println(d.order());
    }
}

What is asked.

Both lines.

Idea.

Search for each body starting at the class Latte and walking upwards.

  1. d.serve(): Latte has serve(), so it returns steam, pour.
  2. d.order(): Latte has no order(), so the search moves up to Drink.
  3. Drink.order() calls serve() on this, which is still the Latte.
  4. That inner call again finds Latte.serve().

Answer.

steam, pour, then order: steam, pour

Common mistake.

Thinking a call written inside Drink must use Drink.serve().

What if

The program prints steam, pour and order: steam, pour.

  • serve() is deleted from Latte. What prints?
    It prints pour and order: pour.. The search from Latte now ends in Drink for serve().
  • A third line prints d.art(). Compile or not?
    It does not compile.. Drink declares no art(). Dispatch never gets a chance, because the name check comes first.

Upcast, then dispatch

  1. A Drink variable points at a Latte object. The variable and the object keep different types.
  2. Compile time: for d.serve() the compiler checks that Drink declares serve(). It does.
  3. Run time: Java asks the object. A Latte overrides serve(), so that body runs.
  4. Latte does not override order(), so the inherited Drink body runs, with this still the Latte.
  5. Inside the parent's code, serve() means this.serve(). The object decides again.

Now read data and a static method through the same variable. A field is a slot, not a behaviour: both classes declared kind, so the object holds two slots. A static method belongs to the class itself, so there is no object to ask. Read the example, then step through its picture.

Worked example: Fields and static methods

Problem.

main now prints a field, a static method and a field through a cast. What appears?

class Drink {
    String kind = "plain";
    static String shelf() { return "drink shelf"; }
    String serve() { return "pour"; }
    String order() { return "order: " + serve(); }
}
class Latte extends Drink {
    String kind = "latte";
    static String shelf() { return "coffee shelf"; }
    @Override
    String serve() { return "steam, pour"; }
    String art() { return "heart"; }
}
public class Main {
    public static void main(String[] args) {
        Drink d = new Latte();
        System.out.println(d.kind);
        System.out.println(d.shelf());
        System.out.println(((Latte) d).kind);
    }
}

What is asked.

Three lines.

Idea.

For fields and static methods, use the type written in front of the dot.

  1. d.kind: the static type of d is Drink, so the Drink slot holds the answer, plain.
  2. d.shelf(): shelf is static, so Drink.shelf() runs and returns drink shelf.
  3. ((Latte) d).kind: the cast makes the static type Latte, so the other slot is read, latte.

Answer.

plain, drink shelf, latte

Common mistake.

Applying dispatch to everything after the dot.

Fields and static methods ignore the object

  1. The object carries two separate fields named kind: one from each class.
  2. A field is picked at compile time from the static type. d.kind reads plain.
  3. A static method belongs to a class, not to the object. The variable's type picks it.
  4. The cast gives a Latte view of the same object, so now the Latte field is read.

Method call or field read

Instance method

Drink d = new Latte();
String s = d.serve();

Field

Drink d = new Latte();
String s = d.kind;

The difference. Parentheses make it a method call.

Instance methods follow the object; fields and static methods follow the written type.

When this breaks

A child static method with the parent's signature does not override anything. It hides the parent's method, and d.shelf() through a Drink variable still runs the parent's body.

4. final and private

Some members are locked, and some are invisible to the child.

which members a subclass may not replace or even see

A bank lets each account type describe itself, but nobody may change the bank's name, and the audit code must use the bank's own secret routine. How do you say "do not replace this" and "this is mine alone"?

final is a seal: the child can see and use the method, but cannot write a new one. private is a closed drawer: the child cannot even see inside, so it may own a drawer with the same label that has nothing to do with yours. The analogy stops at objects: a sealed variable can still point at a box whose contents change.

Why does this change dispatch? Overriding means a child replaces a method it inherits. A private method is not inherited into the child's view, so there is nothing to replace. The parent's own calls to it are settled at compile time.

Three different locks

WrittenChild may see itChild may replace it
plain methodyesyes, by overriding
final methodyesno: compile error
private methodnoit can only add its own
static methodyesno, it can only hide it

Worked example: Whose secret?

Problem.

What does this print?

class Account {
    private String code() { return "parent code"; }
    String audit() { return code(); }
    final String bank() { return "North Bank"; }
}
class Savings extends Account {
    String code() { return "child code"; }
}
public class Main {
    public static void main(String[] args) {
        Savings s = new Savings();
        System.out.println(s.audit());
        System.out.println(s.code());
        System.out.println(s.bank());
    }
}

What is asked.

Three lines.

Idea.

Check whether the method being called is private in the class where the call is written.

  1. s.audit() runs the inherited Account.audit().
  2. Inside it, code() is private in Account, so it means Account.code(): parent code.
  3. s.code() is a call on a Savings, which declares its own code(): child code.
  4. bank() is inherited and sealed: North Bank.

Answer.

parent code, child code, North Bank

Common mistake.

Dispatching code() to the child from inside audit().

What if

The Account program prints parent code, child code, North Bank.

  • The word private is removed from Account.code(). What is the first line now?
    It prints child code.. The child now overrides the method, so the call inside audit() dispatches on the Savings object.
  • Savings adds String bank() { return "mine"; }. Compile or not?
    It does not compile.. A final method cannot be overridden.
  • main declares Account s = new Savings(); and keeps the same three calls. Compile or not?
    It does not compile.. s.code() now asks Account for code(), which is private there.

Worked example: Using a private value without touching it

Problem.

Clicker calls bump() twice. The step size is private and static. What prints?

class Counter {
    private static int step = 5;
    int total;
    final int bump() {
        total = total + step;
        return total;
    }
}
class Clicker extends Counter {
    int twice() {
        bump();
        return bump();
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(new Clicker().twice());
    }
}

What is asked.

The number.

Idea.

An inherited method may use private members of its own class on the child's behalf.

  1. new Clicker() starts with total equal to 0.
  2. bump() is final but inherited, so the child may call it.
  3. The first call makes total 5 and the second makes it 10.
  4. twice() returns the result of the second call.

Answer.

10

Common mistake.

Saying the program fails because Clicker cannot see step. It never names step.

A sealed arrow, an open box

Change the contents

final int[] jar = {3, 4};
jar[0] = 30;

Change the arrow

final int[] jar = {3, 4};
jar = new int[2];

The difference. An index on the left side of the assignment.

final freezes the variable, not the object it points at.

When this breaks

"final means nothing can change" is false. The final array below accepts a new first element, and the program prints the sum with the new value.

A final array that changes

public class Main {
    public static void main(String[] args) {
        final int[] jar = {3, 4};
        jar[0] = 30;
        System.out.println(jar[0] + jar[1]);
    }
}

5. toString and equals

Printing and comparing an object call methods you can replace.

the two methods every object inherits from Object

You print a coin and want to read Coin(5). You compare two cinema seats with the same row and number and want true. Out of the box Java gives you neither, because it cannot know which fields matter to you.

Every class inherits from Object. Its toString() returns the class name, an @ sign and a hexadecimal number. Its equals(Object) answers true only for the very same object. These are ordinary methods, so you replace them by overriding, and the rules of overriding apply in full.

Why must the header match exactly? println and the library's lists only know Object. They call toString() and equals(Object). A method with another header is invisible to them. Also, an override may not be less visible than the method it replaces, and both of these are public.

Worked example: Print a coin

Problem.

What does this print?

class Coin {
    private final int value;
    Coin(int v) { value = v; }
    @Override
    public String toString() { return "Coin(" + value + ")"; }
}
public class Main {
    public static void main(String[] args) {
        Coin c = new Coin(5);
        System.out.println(c);
        System.out.println("kept " + c);
    }
}

What is asked.

Two lines.

Idea.

Both println(c) and "kept " + c turn the object into text by calling toString().

  1. println(c) calls c.toString(), which returns Coin(5).
  2. "kept " + c also calls toString() before joining the texts.

Answer.

Coin(5), then kept Coin(5)

Common mistake.

Writing a void method that prints. toString must return the text.

What if

The Coin program prints Coin(5) and kept Coin(5).

  • The word public is removed from toString. Compile or not?
    It does not compile.. Package access is weaker than public, and an override cannot reduce access.
  • The method is renamed tostring and @Override is removed. What kind of text prints first?
    It prints Coin@ followed by hexadecimal digits.. Java names are case-sensitive. The inherited toString() is still in charge.
  • The return type becomes void, with a print inside. Compile or not?
    It does not compile.. The signature equals toString() in Object, but void cannot replace String.

Now equality. Because the parameter is an Object, the body does three things in order: test that the argument is a seat, cast it so the compiler lets you reach the fields, then compare field by field. Text fields need equals, because == compares arrows, and equal text may sit in two different objects.

Worked example: Two seats, one place

Problem.

b is built from a fresh copy of the text C. What are the three lines?

class Seat {
    private final String row;
    private final int num;
    Seat(String row, int num) { this.row = row; this.num = num; }
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Seat)) return false;
        Seat other = (Seat) o;
        return num == other.num && row.equals(other.row);
    }
}
public class Main {
    public static void main(String[] args) {
        Seat a = new Seat("C", 7);
        Seat b = new Seat(new String("C"), 7);
        System.out.println(a == b);
        System.out.println(a.equals(b));
        System.out.println(a.equals("C7"));
    }
}

What is asked.

Three boolean lines.

Idea.

== compares the arrows; this equals compares the contents.

  1. a and b are two objects, so a == b is false.
  2. In a.equals(b) the test passes, the cast gives other, the numbers match and row.equals compares the letters: true.
  3. The argument "C7" is a String, so the test fails and the method returns false.

Answer.

false, true, false

Common mistake.

Comparing row == other.row. The two row texts are different objects here.

One surprise to settle before the past questions. Two equal literals (text written directly in the code, in quotes) are stored once and shared. This sharing is called interning, so == happens to be true for them. new String(...) always makes a separate object.

Worked example: One literal or a new object

Problem.

What are the three lines?

public class Main {
    public static void main(String[] args) {
        String a = "mint";
        String b = "mint";
        String c = new String("mint");
        System.out.println(a == b);
        System.out.println(a == c);
        System.out.println(a.equals(c));
    }
}

What is asked.

Three boolean lines.

Idea.

Count the string objects, then ask which operator looks at the letters.

  1. a and b come from the same literal, so both reach one object: a == b is true.
  2. c was made with new, a second object: a == c is false.
  3. equals compares the letters: true.

Answer.

true, false, true

Common mistake.

Saying == is always false for two string variables, or always safe because it worked with literals.

Identity or contents

==

Seat a = new Seat("C", 7);
Seat b = new Seat("C", 7);
boolean same = a == b;

equals

Seat a = new Seat("C", 7);
Seat b = new Seat("C", 7);
boolean same = a.equals(b);

The difference. The operator against the method call.

== asks "one object?"; an overridden equals asks "same contents?".

When this breaks

boolean equals(Tag other) looks right but is an overload. As soon as the argument's written type is Object, the inherited identity test runs instead.

The overloaded equals

class Tag {
    private final int id;
    Tag(int id) { this.id = id; }
    public boolean equals(Tag other) { return other != null && id == other.id; }
}
public class Main {
    public static void main(String[] args) {
        Tag a = new Tag(9);
        Tag b = new Tag(9);
        Object o = b;
        System.out.println(a.equals(b));
        System.out.println(a.equals(o));
    }
}

6. Static type, casts and instanceof

The compiler checks the written type; the running program checks the object.

what a line may call, and when a cast is safe

You are handed a flute, a metal stand and a harp, one at a time. One method must accept all three, so its parameter is written Object. Now you want every instrument to play. The compiler only knows each item is "some object". What may you ask of it?

Think of parcels labelled only "item". The warehouse rules let you do only what every item allows, until you relabel a parcel. Relabelling does not change what is inside; if the label turns out wrong when you open it, you have a problem. The analogy stops here: Java checks the label at the moment you relabel it: the cast itself fails, even if you never use the result.

Why two checks? The compiler cannot know what an Object variable will hold, so it allows only Object methods. A cast is your claim that the object is more specific. The compiler accepts a claim that could be true, and the running program verifies it.

Three outcomes, never mixed

LineResult
item.play() on an Objectcompilation error
((Harp) item).play() on a Flute objectcompiles, then throws ClassCastException
((Playable) item).play() on a Flute objectruns

Worked example: Guarded cast

Problem.

What does the shelf program print?

interface Playable { String play(); }
class Flute implements Playable {
    public String play() { return "toot"; }
}
class Harp implements Playable {
    public String play() { return "pluck"; }
}
class Stand { }
public class Main {
    static String sound(Object item) {
        if (!(item instanceof Playable)) {
            return "silent";
        }
        return ((Playable) item).play();
    }
    public static void main(String[] args) {
        System.out.println(sound(new Flute()));
        System.out.println(sound(new Stand()));
        System.out.println(sound(new Harp()));
    }
}

What is asked.

Three lines.

Idea.

Test the object, then cast to the type that has the method.

  1. sound receives a Flute: the test passes, so the cast runs and returns toot.
  2. A Stand does not fit, so the method returns silent before any cast.
  3. A Harp fits: pluck.

Answer.

toot, silent, pluck

Common mistake.

Casting to Flute, which only the first item fits.

What if

The shelf program prints toot, silent, pluck.

  • Both the test and the cast say Harp instead of Playable. What prints?
    It prints silent, silent, pluck.. Only the third object fits Harp.
  • The whole if block is removed, leaving only the cast and call. What happens?
    It prints toot and then throws ClassCastException.. The second cast meets a Stand. Output printed before the failure stays printed.
  • The second call becomes sound(null). What is the second line?
    It prints silent.. null instanceof anything is false.

One parameter, three objects

  1. The Flute passes the test, so the cast is safe and play() runs.
  2. A Stand is not Playable. The cast is never attempted.
  3. The Harp passes the same test, and its own play() body runs.

The same test works on the elements of an Object[] array, because each element is also written as Object. This loop counts the instruments without calling them.

Counting instruments in a mixed array

interface Playable { }
class Flute implements Playable { }
class Harp implements Playable { }
public class Main {
    public static void main(String[] args) {
        Object[] bag = {new Harp(), "reed", new Flute()};
        int found = 0;
        for (int i = 0; i < bag.length; i++) {
            if (bag[i] instanceof Playable) {
                found++;
            }
        }
        System.out.println(found + " of " + bag.length);
    }
}

Worked example: The compiler believes you

Problem.

A Van is cast to a Bike. Compile error, or something else?

class Vehicle { }
class Bike extends Vehicle {
    String ring() { return "ding"; }
}
class Van extends Vehicle { }
public class Main {
    public static void main(String[] args) {
        Vehicle v = new Van();
        System.out.println("start");
        Bike b = (Bike) v;
        System.out.println(b.ring());
    }
}

What is asked.

The output and the ending.

Idea.

A downcast along the family tree compiles; the object is checked at run time.

  1. v is written as Vehicle. A Vehicle might be a Bike, so the compiler accepts (Bike) v.
  2. start is printed.
  3. At run time the object is a Van, which is not a Bike.
  4. The cast throws ClassCastException; the last line never runs.

Answer.

start, then ClassCastException

Common mistake.

Calling this a compilation error.

One class or the shared interface

Cast to a class

((Flute) item).play();

Cast to the interface

((Playable) item).play();

The difference. The type inside the parentheses.

In a loop over mixed objects, cast to a type that all of them belong to.

When this breaks

"Any cast compiles" is false. If two classes are unrelated, such as String and Integer, no object can be both, so the compiler rejects the cast.

7. Abstract classes and interfaces

Some types describe work that another class must finish.

types that promise methods, and what happens when two promises meet

Every plant needs care, and care always starts with water. What else a plant needs depends on the plant. A parent class can write the shared part and leave one blank for each child to fill.

An abstract class is a recipe with a missing step. You cannot cook from it, so new is refused. A child that fills every blank is a complete recipe. An interface is a list of promised steps that any class can sign, and a class can sign several. The recipe analogy stops at state: abstract classes can have fields and constructors; interfaces cannot hold per-object fields.

Why the strictness? If an object existed with a blank step, a call to that step would have no body to run. The compiler prevents this at the moment the class is declared, not when the call is made.

Worked example: Parent calls the blank

Problem.

What does this print?

abstract class Plant {
    abstract String need();
    String care() { return "water; " + need(); }
}
class Cactus extends Plant {
    @Override
    String need() { return "sun"; }
    @Override
    String care() { return super.care() + "; rarely"; }
}
public class Main {
    public static void main(String[] args) {
        Plant p = new Cactus();
        System.out.println(p.care());
    }
}

What is asked.

The line.

Idea.

super.care() runs the parent body, and the call to need() inside it still dispatches.

  1. p.care() dispatches to Cactus.care().
  2. It calls super.care(), the body in Plant.
  3. That body calls need(), which dispatches to Cactus.need(): sun.
  4. Plant.care() returns water; sun, and the child appends ; rarely.

Answer.

water; sun; rarely

Common mistake.

Stopping after the parent text, or expecting super.care() to use a parent need().

What if

The plant program prints water; sun; rarely.

  • need() is deleted from Cactus. Compile or not?
    It does not compile.. Cactus would be a creatable class with a method that has no body.
  • main says new Plant(). Compile or not?
    It does not compile.. An abstract class cannot be created.
  • care() is deleted from Cactus. What prints?
    It prints water; sun.. The inherited body runs, and it still calls the child's need().

Interfaces may give a body too. A default method is inherited by implementing classes. A static method is not: it is called only through the interface's own name. What if two interfaces offer the same default?

Worked example: Two defaults, one answer

Problem.

What does this print?

interface Camera {
    default String mode() { return "photo"; }
    static String maker() { return "LensCo"; }
}
interface Recorder {
    default String mode() { return "audio"; }
}
class Gadget implements Camera, Recorder {
    @Override
    public String mode() {
        return Camera.super.mode() + "+" + Recorder.super.mode();
    }
}
public class Main {
    public static void main(String[] args) {
        Camera c = new Gadget();
        System.out.println(c.mode());
        System.out.println(Camera.maker());
    }
}

What is asked.

Two lines.

Idea.

The class settles the conflict; Interface.super.method() picks a particular default.

  1. Gadget overrides mode(), so the clash is resolved and the class compiles.
  2. c.mode() runs the class body, which returns photo+audio.
  3. Camera.maker() is a static call through the interface name: LensCo.

Answer.

photo+audio, then LensCo

Common mistake.

Expecting the first interface listed to win.

Two defaults, one class must decide

  1. Both interfaces offer a body for mode(). Java refuses to guess, so Gadget must write its own.
  2. c.mode() dispatches on the object, so the class's own body runs.
  3. Camera.super.mode() names exactly one default and runs it.
  4. The second call picks the other default. The class joins the two results.

Worked example: A class against a default

Problem.

Mango inherits price() twice, and a default calls it. Which price is printed?

interface Priced {
    default int price() { return 0; }
    default String label() { return "costs " + price(); }
}
class Stock {
    public int price() { return 25; }
}
class Mango extends Stock implements Priced { }
public class Main {
    public static void main(String[] args) {
        Priced p = new Mango();
        System.out.println(p.label());
    }
}

What is asked.

The output.

Idea.

A method inherited from a class beats an equal default from an interface, even for calls made inside the interface.

  1. Stock gives Mango a public price() with a body.
  2. Priced offers a default with the same signature, so the class method wins and there is no error.
  3. p.label() has no class version, so the default label() runs.
  4. Its call price() dispatches on the Mango and finds the class method, 25.

Answer.

costs 25

Common mistake.

Reporting a conflict, or thinking a default calls its own interface's price().

Default against default, class against default

Two interfaces

class Mango implements Priced, Taxed { }

Class and interface

class Mango extends Stock implements Priced { }

The difference. One of the two sources is a class.

Equal defaults from unrelated interfaces need your override; a class method wins by itself.

When this breaks

"A class method wins" still demands a legal method. If the superclass method is not public, it cannot stand in for an interface method, and the subclass does not compile.

8. Callbacks and private inner classes

An object can be called back later, and a hidden class can still be used.

passing yourself to another object, and hiding a class behind a public type

A kitchen timer should tell an egg every time a minute passes, so the egg can be turned. The timer was built to work with anything, not only eggs. How can it call back without knowing what an Egg is?

The egg leaves a phone number: a reference to itself, typed as the interface Tick. The timer rings at(minute) on it. The analogy stops at timing: here the call is an ordinary method call, so the timer's loop pauses until the callback returns.

Why an interface? The timer should depend only on what it needs, one method named at. Any class that provides it can be passed in. So can a lambda, a short unnamed method body such as m -> System.out.println(m), which Java turns into an object for an interface with exactly one abstract method.

Worked example: Order of a callback

Problem.

What does the timer program print?

interface Tick { void at(int minute); }
class Timer {
    static void run(int minutes, Tick listener) {
        for (int m = 1; m <= minutes; m++) {
            listener.at(m);
        }
        System.out.println("timer done");
    }
}
class Egg implements Tick {
    private int turns;
    public void at(int minute) {
        turns++;
        System.out.println("turn " + turns + " at minute " + minute);
    }
}
public class Main {
    public static void main(String[] args) {
        Timer.run(2, new Egg());
    }
}

What is asked.

Three lines, in order.

Idea.

Trace nested calls: the inner method finishes before the loop continues.

  1. main passes a new Egg to Timer.run with 2 minutes.
  2. At m = 1, listener.at(1) runs Egg.at: turns becomes 1 and the first line prints.
  3. At m = 2 the same object is called again: turns becomes 2.
  4. The loop ends and run prints timer done.

Answer.

turn 1 at minute 1, turn 2 at minute 2, timer done

Common mistake.

Printing the callbacks after the whole method has finished, or restarting turns for each call.

What if

The program prints two turn lines and then timer done.

  • The line listener.at(m); is deleted. What prints?
    It prints only timer done.. Passing a reference does nothing by itself; only a call runs the callback.
  • main instead says Timer.run(2, m -> System.out.println("beep " + m)); What prints?
    It prints beep 1, beep 2, timer done.. The lambda supplies the single method of Tick.

A callback goes out and comes back

  1. main creates an Egg. Its turns field starts at 0. It is about to call Timer.run.
  2. run receives a reference to the egg. It only knows that the object is a Tick.
  3. listener.at(m) calls back into the egg. run is paused underneath.
  4. The loop calls the same object again, so its field keeps counting.
  5. The last callback has returned. The loop ends and run prints its own line.

Now the second move. A playlist wants to hand out its songs one by one without showing its array. It declares a private inner class that walks the array, and returns it as a Cursor. Being inner, the walker can read the playlist's private songs.

Worked example: A hidden walker

Problem.

Walk is private. Can main still use it, and what prints?

interface Cursor {
    boolean more();
    String take();
}
class Playlist {
    private final String[] songs = {"dawn", "noon"};
    public Cursor cursor() { return new Walk(); }
    private class Walk implements Cursor {
        private int at;
        public boolean more() { return at < songs.length; }
        public String take() { return songs[at++]; }
        public int position() { return at; }
    }
}
public class Main {
    public static void main(String[] args) {
        Cursor c = new Playlist().cursor();
        while (c.more()) {
            System.out.println(c.take());
        }
    }
}

What is asked.

The output.

Idea.

main never writes the name Walk; it works through Cursor.

  1. cursor() is a factory method inside Playlist, so it may write new Walk().
  2. It returns the object typed as Cursor, which main can see.
  3. more() and take() are declared in Cursor, so main may call them.
  4. The loop prints dawn, then noon, and stops when at reaches 2.

Answer.

dawn, then noon

Common mistake.

Saying the program cannot compile because the class is private.

Hold it or name it

Through the interface

Cursor c = new Playlist().cursor();

By the private name

Playlist.Walk c =
    (Playlist.Walk) new Playlist().cursor();

The difference. The type written on the left (and in the cast).

A private class may be used through a visible type, never named from outside.

When this breaks

Hiding is by visible type. position() is public inside Walk, yet c.position() does not compile in main, because Cursor does not declare it.

Practise this topic →

Weeks covering this topic

Other Java topics