Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 7

Animal a = new Dog(); a.sound();

Why the Dog version runs — the mechanism, step by step

22m60 XP
→→→

What you'll be able to do

  • Separate the reference type from the object's actual type
  • Explain what the compiler decides and what the JVM decides
  • Predict which implementation runs for any parent-typed reference
  • Know why fields do not behave polymorphically
1

Dynamic Method Dispatch

Two types, two different questions

One line of code, two types: `Animal a = new Dog();`. Everything in this lesson follows from noticing that.

The famous two lines

Main.java
1Animal a = new Dog();
2a.sound();
Animal a = new Dog();
Two different types in one statement. Animal is the reference type (what the variable is declared as). Dog is the object type (what was actually created on the heap). The assignment is legal because a Dog IS-A Animal — this is *upcasting*, and it is automatic.
a.sound();
Now two separate decisions happen. At compile time Java asks: does the type Animal have a method sound()? Yes → the call is legal. At run time the JVM asks: what is this object really? A Dog → run Dog.sound(). That runtime step is dynamic method dispatch.

Who decides what

QuestionDecided byBased on
Is this call even allowed?the compilerthe reference type (Animal)
Which method body runs?the JVM, at run timethe object's real type (Dog)
Which overloaded version is picked?the compilerthe argument types (Module 9)
Which field is read?the compilerthe reference type — fields are never polymorphic

Memorise the first two rows as one sentence: *the reference type decides what you may call, the object decides what actually happens.*

What is really in memory

Stack
a (type Animal)→→ Dog#1
Heap
dog1: Dog
actual classDog
sound()Dog's override
eat()inherited from Animal

The variable is just a labelled arrow typed `Animal`. The object on the heap never forgets that it is a Dog — that is the information the JVM uses to dispatch the call.

What happens when `a.sound()` executes

  1. The compiler looks up sound() in Animal. Found, no arguments, accessible → the code compiles. (Had you written a.fetch(), compilation would fail here — Animal has no fetch.)
  2. At run time the JVM follows the reference to the object and reads its actual class: Dog.
  3. It looks for sound() starting at Dog. Found an override → that body runs. Had Dog not overridden it, the search would continue up to Animal.
  4. Inside that body, this refers to the Dog object — so any further unqualified calls dispatch dynamically too.
Prove it yourself

Run it: the Dog version wins. Now uncomment `a.fetch();` — the error proves the compiler only sees `Animal`.

Output
Press Run to execute this example.

So why is this useful, and not just clever?

Because it lets you write code against the parent type and have it work with subclasses that did not exist when you wrote it. ``java static void checkout(Payment payment) { payment.pay(); } ` This method will correctly handle CardPayment, CashPayment, and the CryptoPayment your team adds next year — without a single edit, and without one if` checking the type. That is the practical value of overriding + dynamic dispatch, and it is what Module 8 formalises as polymorphism.

The exception: fields are resolved by the reference type
Main.java
1class Parent { String label = "parent"; }
2class Child extends Parent { String label = "child"; }
3
4Parent p = new Child();
5System.out.println(p.label); // prints "parent", not "child"!
Only *methods* are dispatched dynamically. A field with the same name in a child **hides** the parent's field, and which one you get depends on the reference type. Never do this on purpose — but expect the question in an interview.

Common mistakes

WrongAnimal a = new Dog(); a.fetch();
WhyThe compiler only knows the reference type `Animal`, which has no `fetch()`.
FixDeclare it as `Dog a = new Dog();`, or cast after checking: `if (a instanceof Dog) ((Dog) a).fetch();` (Module 8).
WrongExpecting `a.sound()` to print the Animal version because `a` is declared `Animal`.
WhyThe declared type never chooses the body — the object does.
FixAsk 'what was created with `new`?' That class's override wins.
WrongAssuming fields behave like methods.
WhyFields are bound at compile time by the reference type; only methods are dynamically dispatched.
FixKeep fields private and expose behaviour — then the question never arises.

Lesson playground

Free practice

An outbox of Notification references holding different subclasses. Add a `PushNotification` and put it in the array — the loop needs no change at all.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

One method, three different objects. What is printed?

Main.java
1class Payment {
2 void pay() {
3 System.out.println("Generic payment");
4 }
5}
6
7class CardPayment extends Payment {
8 @Override
9 void pay() {
10 System.out.println("Paid by card");
11 }
12}
13
14class CashPayment extends Payment {
15 @Override
16 void pay() {
17 System.out.println("Paid by cash");
18 }
19}
20
21public class Main {
22 static void checkout(Payment payment) {
23 payment.pay();
24 }
25
26 public static void main(String[] args) {
27 checkout(new CardPayment());
28 checkout(new CashPayment());
29 checkout(new Payment());
30 }
31}

Summary

  • `Animal a = new Dog();` has a reference type (`Animal`) and an object type (`Dog`).
  • The compiler uses the reference type to decide what is callable; the JVM uses the object to decide which body runs.
  • This lets one piece of code work with subclasses written later — no `if` on types.
  • Fields (and static methods) are not polymorphic; instance methods are.