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.

Last updated: November 2026

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 through pet. If Animal has no accessible bark() member, pet.bark() fails compilation—even though pet points to a Dog at runtime.
  • Object Type (Dog, right-hand side): Checked at runtime. When an overridable instance method declared on Animal is invoked, the JVM uses virtual method invocation (dynamic dispatch) to locate and execute Dog'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 KindMechanismResolved ByTiming
Overridden instance methodVirtual method invocationRuntime object typeRuntime
static method with same signatureMethod hidingCompile-time reference typeCompile time
Instance or static field with same nameField hidingCompile-time reference typeCompile 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:

  1. Square(int) invokes super() (Shape()), which runs before Square's own instance field initializers (like private int side = 5;) and before Square's constructor body.
  2. Inside Shape(), calling an overridable method draw() dynamically dispatches to Square.draw()—because the runtime object already has class Square!
  3. At that moment, Square.side still has the default value 0.
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.

Loading diagram...
Compile-Time Resolution vs. Runtime Dynamic Dispatch
Test Your Knowledge

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?

A

20S20

B

10B20

C

10S20

D

10B10

Test Your Knowledge

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();
    }
}
A

Prints P Done

B

Prints Ready Done

C

Prints Done Done

D

Prints null Done

Test Your Knowledge

Which statement about reference types and runtime object types in Java is true?

A

The compile-time reference type determines which methods are legal to call, while the runtime object type determines which overridden instance method executes

B

Assigning a subclass object to a superclass variable converts the runtime object into an instance of the superclass

C

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

D

An array declared as Animal[] populated with new Dog[2] throws ClassCastException during array assignment

Sections you finish are checked off in the contents.