9.2 Polymorphism, Reference Type vs. Object Type & Dispatch
Key Takeaways
The compile-time reference type acts as the compiler contract determining which fields and methods are visible to call
The runtime object type determines which overridden instance method executes via virtual method invocation (dynamic dispatch)
Static method calls and field accesses are resolved at compile time using the reference type, never the runtime object type
Polymorphic parameters and arrays such as
Animal[] zoo = {new Dog(), new Cat()}let the same operation work across subtypes.A virtual call on the object under construction from a superclass constructor can reach the subclass override before the subclass instance initializers run.
Polymorphism, Reference Type vs. Object Type & Dispatch
In Java, an object created with new Dog() has a fixed runtime object type (Dog) that never changes during its lifetime. However, that single object can be accessed through variables of different compile-time reference types, such as Dog, Animal, or Object. Polymorphism is the ability of code written against a general reference type to invoke specialized behavior provided by the actual object at runtime.
Compile-Time Reference Type vs. Runtime Object Type
Consider the declaration:
Animal pet = new Dog();
The Java compiler and the Java Virtual Machine (JVM) inspect two completely different sides of this assignment:
- Reference Type (
Animal, left-hand side): Checked at compile time. It defines which fields and methods the caller is permitted to access throughpet. IfAnimalhas no accessiblebark()member,pet.bark()fails compilation—even thoughpetpoints to aDogat runtime. - Object Type (
Dog, right-hand side): Checked at runtime. When an overridable instance method declared onAnimalis invoked, the JVM uses virtual method invocation (dynamic dispatch) to locate and executeDog's overridden implementation.
class Animal {
public void speak() { System.out.println("..."); }
}
class Dog extends Animal {
@Override
public void speak() { System.out.println("Woof"); }
public void bark() { System.out.println("Loud Woof"); }
}
public class DispatchDemo {
public static void main(String[] args) {
Animal pet = new Dog();
pet.speak(); // Compiles (Animal has speak); prints "Woof" (Dog runtime type)
// pet.bark(); // DOES NOT COMPILE: Animal has no bark() method
}
}
Notice how the compiler makes zero assumptions about what concrete object pet holds at runtime. Even on the line right after Animal pet = new Dog();, the compiler only trusts the declared type Animal.
Polymorphic Parameters, Return Types & Arrays
Polymorphism shines when methods and collections work on a shared supertype rather than hardcoding every concrete class:
class Cat extends Animal {
@Override
public void speak() { System.out.println("Meow"); }
}
public class Clinic {
public static void checkup(Animal patient) { // Polymorphic parameter
patient.speak();
}
public static void main(String[] args) {
Animal[] zoo = { new Dog(), new Cat(), new Animal() };
for (Animal a : zoo) {
checkup(a); // Prints: Woof, then Meow, then ...
}
}
}
Array Covariance Pitfall
Java arrays are covariant: a Dog[] reference can be assigned to an Animal[] variable. The actual array type is still Dog[], with component type Dog. Storing a Cat into that Animal[] variable compiles cleanly—because Cat is an Animal—and then throws ArrayStoreException at runtime:
Dog[] dogs = new Dog[2];
Animal[] animals = dogs; // Compiles: arrays are covariant
animals[0] = new Cat(); // Compiles, but throws ArrayStoreException at runtime!
Instance Method Overriding vs. static & Field Hiding
The single most heavily tested distinction in Java polymorphism is which members use runtime dispatch and which use compile-time resolution.
| Member Kind | Mechanism | Resolved By | Timing |
|---|---|---|---|
| Overridden instance method | Virtual method invocation | Runtime object type | Runtime |
static method with same signature | Method hiding | Compile-time reference type | Compile time |
Instance or static field with same name | Field hiding | Compile-time reference type | Compile time |
Java has no field overriding and no static method overriding. Let us trace all three behaviors side by side in one complete program:
class Account {
public String label = "BaseAccount";
public static String category() { return "Generic"; }
public String format() { return "Account: " + label; }
}
class SavingsAccount extends Account {
public String label = "SavingsAccount"; // Hides Account.label
public static String category() { return "Savings"; } // Hides Account.category()
@Override
public String format() { return "Savings: " + label; } // Overrides Account.format()
}
public class HidingTrace {
public static void main(String[] args) {
SavingsAccount sa = new SavingsAccount();
Account acc = sa; // Same object, two different reference types
System.out.println(acc.label); // 1. "BaseAccount" (reference type Account)
System.out.println(sa.label); // 2. "SavingsAccount" (reference type SavingsAccount)
System.out.println(acc.category()); // 3. "Generic" (reference type Account)
System.out.println(sa.category()); // 4. "Savings" (reference type SavingsAccount)
System.out.println(acc.format()); // 5. "Savings: SavingsAccount" (object type SavingsAccount!)
}
}
Look closely at line 5: acc.format() dispatches at runtime to SavingsAccount.format(). Inside SavingsAccount.format(), unqualified label resolves to SavingsAccount.label ("SavingsAccount"), printing "Savings: SavingsAccount". The declarations for acc.label and acc.category() both come from type Account. Reading the instance field still requires an object and reads that object’s Account.label field. The static call does not require an instance.
Tip
When tracing ref.member, find the accessible declaration or applicable overload at compile time. For an ordinary virtual invocation, use the receiver’s class to find the implementation of that selected signature. A super call or a private method does not use ordinary dynamic dispatch.
The Constructor Calling Overridable Methods Trap
Because dynamic dispatch is active even before a subclass finishes constructing, calling an overridable method from a superclass constructor is a notorious source of subtle bugs and exam questions.
When new Square(10) runs:
Square(int)invokessuper()(Shape()), which runs beforeSquare's own instance field initializers (likeprivate int side = 5;) and beforeSquare's constructor body.- Inside
Shape(), calling an overridable methoddraw()dynamically dispatches toSquare.draw()—because the runtime object already has classSquare! - At that moment,
Square.sidestill has the default value0.
class Shape {
Shape() {
draw(); // Calls overridden method during superclass construction!
}
void draw() {
System.out.println("Shape.draw");
}
}
class Square extends Shape {
private int side = 5; // Runs AFTER Shape() completes!
Square(int side) {
// Implicit super() runs here first
this.side = side;
}
@Override
void draw() {
System.out.println("Square side = " + side);
}
public static void main(String[] args) {
new Square(10);
}
}
Exact output: Square side = 0 (not 5 and not 10!). When Shape() invokes draw(), Square.side has only been default-initialized to 0. Only after Shape() finishes do side = 5 and this.side = 10 execute.
Caution
Never call overridable instance methods from a constructor. Restrict constructor helper calls to private, final, or static methods so subclass overrides cannot observe uninitialized fields.
Given:
class Base {
int val = 10;
static String tag() { return "B"; }
int getVal() { return val; }
}
class Sub extends Base {
int val = 20;
static String tag() { return "S"; }
@Override int getVal() { return val; }
}
What does Base b = new Sub(); System.out.println(b.val + b.tag() + b.getVal()); print?
20S20
10B20
10S20
10B10
What happens when the following code is compiled and executed?
class Parent {
Parent() { print(); }
void print() { System.out.print("P "); }
}
class Child extends Parent {
String name = "Ready";
Child() { name = "Done"; }
@Override void print() { System.out.print(name + " "); }
public static void main(String[] args) {
new Child().print();
}
}
Prints P Done
Prints Ready Done
Prints Done Done
Prints null Done
Which statement about reference types and runtime object types in Java is true?
The compile-time reference type determines which methods are legal to call, while the runtime object type determines which overridden instance method executes
Assigning a subclass object to a superclass variable converts the runtime object into an instance of the superclass
Calling a subclass-only method through a superclass variable compiles without a cast as long as the runtime object is an instance of the subclass
An array declared as Animal[] populated with new Dog[2] throws ClassCastException during array assignment
Sections you finish are checked off in the contents.