The Role of the Reference Type at Compile Time
What you'll learn: How the reference variable's declared type controls what methods you can call, even though it doesn't control which implementation actually runs.
Compile Time vs. Runtime: Two Different Checks
When you work with polymorphic references in Java, the compiler and the JVM each have different jobs:
- At compile time, Java checks whether a method exists on the reference type (the declared type of your variable).
- At runtime, Java calls the method implementation from the actual object type (the object the reference points to).
Think of it like a restaurant menu: the reference type is the menu you're handed—it determines what you can order. But the kitchen (runtime) determines what recipe actually gets cooked based on what you actually ordered.
The Compiler Uses the Reference Type
Animal myAnimal = new Dog(); // Upcast: Dog object, Animal reference
myAnimal.eat(); // ✓ Compiles: eat() exists in Animal
myAnimal.bark(); // ✗ Compile error: bark() not in Animal
Even though the actual object is a Dog that has a bark() method, the compiler only sees the Animal reference type. Since Animal doesn't declare bark(), the code won't compile.
However, if eat() is overridden in Dog, calling myAnimal.eat() will execute Dog's implementation at runtime—dynamic dispatch handles that.
Why This Matters
This separation ensures type safety: the compiler guarantees you're only calling methods that should exist, while dynamic dispatch ensures the correct version runs based on the actual object.
Key Takeaway: The reference type acts as a compile-time contract specifying which methods are visible, while the actual object type determines which implementation executes at runtime.