Method Dispatch and Casting

exercises
tutorial
java
polymorphism
casting

Applied class exercises for week 4, covering java-polymorphism (dynamic method dispatch) and java-casting in more depth.

On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "Car.topSpeed()"), then click Run Code to check it. In the PDF, the Working callout is shown as a static answer key instead (interactive checking needs a browser).

The five rules of method dispatch

Method dispatch follows five rules. Everything else in the class is an application of them:

  1. The compiler deduces an apparent type (also called a compile-time type) for each object, using type information from variable and method declarations.
  2. Each object also has an actual type (also called a runtime type), obtained when it is created by new: the type of the class that constructs it.
  3. The compiler ensures the apparent type it deduces is always the actual type, or a superclass of the actual type.
  4. The compiler determines what calls are legal based on the object’s apparent type.
  5. Dispatching causes method calls to go to the object’s actual code — that is, the code provided by its actual type.

Figure 1: The two types every reference carries, and what each one decides, on the declaration C variable = new R();, where C is a superclass of R or is R. The apparent type C decides whether variable.method() is legal; the actual type R decides which code it runs.

Rules 4 and 5 are the whole exercise: legality is decided from the apparent type, the code that runs comes from the actual type. The two are settled at different times and can disagree.

Question 1 — Apparent type vs actual type

class Animal {
    void eat() {...}
}
class Lion extends Animal {}
class Dog extends Animal implements Pet {
    void eat() {...}
    void eat(int howMuch) {...}
}
class Poodle extends Dog {}
interface Pet {}

A diagram makes it easier to see how the classes are related and which method will be invoked:

Figure 2: The Question 1 hierarchy. Superclass above; a solid rectangle for a class and a dashed rectangle for an interface; the class name in bold serif over a rule, members below as + name(); a solid line for extends and a dashed line for implements, both with the same filled arrowhead. The SOLID diagrams draw implements with an open arrowhead instead.

What happens when you call simba.eat(200), given Lion simba = new Lion();?

simba’s apparent AND actual type is Lion, which has no eat(int) method (only the no-arg eat() inherited from Animal) — the compiler rejects the call outright, since legality is checked against the apparent type’s available methods (rule 4).

The full table, one line at a time:

Statement Outcome
Dog evie = new Dog(); OK
Animal animal = evie; OK (upcast, implicit)
Lion mufasa = animal; Must be cast. Will fail (an Animal referencing a Dog is never a Lion).
Dog harlee = animal; Must be cast. Will succeed — the cast is written out as if (animal instanceof Dog harlee) ...
Poodle bruiser = evie; Must be cast. Will fail (evie’s actual type is Dog, not Poodle).
Lion simba = new Lion(); OK
Lion scar = new Poodle(); Will not compile — Poodle and Lion share no inheritance relationship.
Pet charley = new Poodle(); OK (Poodle extends Dog, which implements Pet).
Dog lassie = charley; Must be cast. Will succeed.
Animal scooby = charley; Will not compile — Pet is not related to Animal (an interface doesn’t know about unrelated classes).
simba.eat(); OK
simba.eat(200); No method found — compile error.

Task 0 — Draw the hierarchy

Draw a diagram which makes the code below easier to understand.

In the following, all classes, interfaces, and members are public, and many details have been omitted:

class Location {...}

interface RoadLegal {
    int topSpeed();
    boolean licenceRequired();
}

interface PublicTransport {
    double calculateFare(Location start, Location end);
}

class Vehicle {
    int travelTime(Location start, Location end) {...}
    int topSpeed() {...}
}

class HumanPowered extends Vehicle {
    int getWeight() {...}
    int topSpeed() {...}
}

class Motorised extends Vehicle implements RoadLegal {
    int travelTime(Location start, Location end) {...}
    int topSpeed() {...}
    boolean licenceRequired() {...}
}

class Skateboard extends HumanPowered {}

class Bicycle extends HumanPowered implements RoadLegal {
    boolean licenceRequired() {...}
}

class Motorbike extends Motorised {
    int topSpeed() {...}
    int travelTime(Location location) {...}   // overload, not an override
}

class Car extends Motorised {
    int topSpeed() {...}
}

class Taxi extends Car {}

class Bus extends Motorised implements PublicTransport {
    int topSpeed() {...}
    double calculateFare(Location start, Location end) {...}
}

Figure 3: Task 0’s answer. Same conventions as Figure 2: dashed rectangles are interfaces, solid lines are extends, dashed lines are implements, both with a filled arrowhead, superclass above. Only the methods each type actually declares are listed — that is what makes the dispatch questions answerable by eye. Location is drawn floating and unconnected. Motorbike declares travelTime(Location) — one argument — which is an overload of, not an override of, Vehicle.travelTime(Location, Location).

Two things to read off the picture before attempting anything else:

  • RoadLegal is reached twice by different routes — once through Motorised, once directly from Bicycle. So Motorbike, Car, Taxi, Bus and Bicycle are all RoadLegal, but Skateboard is not.
  • Bicycle implements RoadLegal yet declares only licenceRequired(). It satisfies topSpeed() with the one it inherits from HumanPowered.

Task 1 — Does it compile?

For the creation and usage of objects below, indicate whether the statements would compile or not. If it would not compile, explain why.

# Statement(s) Verdict
1 Vehicle bus = new Bus(); Compiles, no error. Bus is implicitly upcast to Vehicle.
2 Motorised skateboard = new Skateboard(); Does not compile. There is no relationship between Motorised and Skateboard, so a Skateboard can never be an instance of Motorised.
3 Motorbike vehicle = new Vehicle(); Does not compile. Going from Vehicle to Motorbike is a downcast, so an explicit cast is required.
4 Motorised motorbike = new Motorbike();
Location destination = new Location();
motorbike.travelTime(destination);
Does not compile. Motorised and its parent classes have no method matching the signature travelTime(Location). The one-argument overload exists only on Motorbike, and legality is judged from the apparent type.
5 Motorbike motorbike = new Motorbike();
Location start = new Location();
Location end = new Location();
motorbike.travelTime(start, end);
Compiles, no error. travelTime() is overloaded in Motorbike, so both the one- and two-Location versions are available through a Motorbike-typed variable.

Bonus:

# Statement(s) Verdict
1 Car car = new Taxi();
Taxi taxi = car;
Does not compile. Going from Car to Taxi is a downcast, so an explicit cast is required.
2 Vehicle bike = new Bicycle();
bike.getWeight();
Does not compile. Vehicle has no method matching the signature getWeight() — it is declared on HumanPowered.
3 Motorised bus = new Bus();
PublicTransport trip = bus;
trip.calculateFare(start, end);
Does not compile. Motorised cannot be implicitly cast into PublicTransport.

Items 4 and 5 are the pair worth memorising. A Motorbike object really does have a one-argument travelTime — item 5 shows both overloads are reachable through a Motorbike-typed variable. Widen the variable to Motorised and the very same object stops accepting the call (item 4), because legality is judged from the apparent type and nothing above Motorbike declares that signature.

Task 2 — Which implementation is called?

For each, what method implementation is actually called? (Assume location1 and location2 are Location objects.)

Vehicle vehicle = new Taxi(); vehicle.topSpeed(); →

Vehicle vehicle = new Bicycle(); vehicle.topSpeed(); →

RoadLegal roadLegal = new Bicycle(); roadLegal.topSpeed(); →

Vehicle vehicle = new Motorbike(); vehicle.travelTime(location1, location2); →

Call Dispatches to
Vehicle vehicle = new Taxi(); vehicle.topSpeed(); Car.topSpeed()
Vehicle vehicle = new Bicycle(); vehicle.topSpeed(); HumanPowered.topSpeed()
RoadLegal roadLegal = new Bicycle(); roadLegal.topSpeed(); HumanPowered.topSpeed()
Vehicle vehicle = new Motorbike(); vehicle.travelTime(location1, location2); Motorised.travelTime(Location, Location)

Read each one off Figure 3: start at the actual type and walk up until you find a box that lists the method.

  • Taxi declares nothing, so topSpeed() comes from Car.
  • Bicycle declares only licenceRequired(), so topSpeed() comes from HumanPowered — and this is unchanged when the apparent type is the RoadLegal interface. Dispatch never consults the apparent type (rule 5).
  • Motorbike overrides topSpeed() and overloads travelTime with a one-argument version, but never overrides the two-argument one, so that call lands on Motorised.

Casting — the three rules

In Java, when changing the apparent type of a value:

  1. If the new apparent type is a superclass of the old apparent type, the cast can be implicit.
  2. If the new apparent type is a subclass of the old apparent type, the cast should be performed via an instanceof check.
  3. If the new apparent type and old apparent type have no inheritance relationship, Java will refuse to compile.

Task 3 — instanceof: compiles? implicit?

Assume that xyz is an instance of class Xyz — e.g. bus is an instance of Bus. For each cast, indicate whether (1) it would compile and (2) it could be implicit.

Expression Compiles Implicit Why
if (bus instanceof Vehicle vehicle) ✓ ✓ Vehicle is a superclass of Bus — rule 1.
if (car instanceof Taxi taxi) ✓ ✗ Taxi is a subclass of Car, so it needs the runtime check — rule 2.
if (motorised instanceof Bicycle bike) ✗ — Motorised and Bicycle are siblings under Vehicle with no relationship — rule 3.
if (motorbike instanceof RoadLegal legal) ✓ ✓ Motorbike extends Motorised, which implements RoadLegal.
if (taxi instanceof Vehicle vehicle) ✓ ✓ Vehicle is a superclass all the way up the Taxi → Car → Motorised → Vehicle chain.

The “Implicit” cell is left blank for the row that does not compile, rather than marked ✗ — there is nothing to decide once the code is rejected.

Task 4 — Where would an electric scooter fit?

If we wanted a class to represent an electric scooter, where would that fit in the hierarchy?

The answer is deliberately open; this is a discussion question. Not all models fit all circumstances, and single inheritance makes this one difficult.

An electric scooter is motorised and human-scale, road-legal in some jurisdictions and not others — and Java gives you exactly one superclass. The escape hatch the rest of the course teaches is to push the shared behaviour into interfaces rather than a class (see java-solid-principles on interface segregation, and week11-tutorial-dependency-inversion).

Where this reappears

The same two-phase rule — overload chosen at compile time from the static types, override resolved at run time from the actual type — comes back in revision Questions 19–21, worked with the BruceWayne/Batman/kapow example. See 2026-05-28-course-summary-and-exam-preparation and 2026-03-12-object-oriented-programming-ii.