Method Resolution Process Overview
What you'll learn: How the JVM decides which method to call, first at compile-time and then at runtime.
How the JVM Resolves Methods
When you call a method on an object reference, the JVM performs a two-step dance to figure out exactly which method should execute. Understanding this process is key to mastering dynamic dispatch and polymorphism.
The Two-Phase Process
Phase 1: Compile-Time Type Checking
First, the Java compiler looks at the reference type (the declared type of your variable) to verify that a method with that signature exists. This is a safety check—if the reference type doesn't have the method, your code won't compile.
Animal myAnimal = new Dog();
myAnimal.makeSound(); // Compiler checks: Does Animal have makeSound()?
The compiler doesn't care what the actual object is; it only checks the reference type (Animal). If Animal declares makeSound(), compilation succeeds. If not, you get a compile error.
Phase 2: Runtime Method Lookup
At runtime, the JVM looks at the actual object's class to find which version of the method to execute. It starts at the object's real class and searches up the inheritance hierarchy until it finds the method implementation.
// Runtime: JVM sees the object is really a Dog
// Looks in Dog class first for makeSound()
// If found, uses Dog's version (dynamic dispatch!)
Why Two Phases?
Think of it like airport security: compile-time checks your ticket is valid (you have permission to board), but runtime checks your actual identity to assign your seat. This combination provides both safety (compile-time) and flexibility (runtime polymorphism).
Key Takeaway: Method resolution happens in two stages—compile-time verifies the method exists on the reference type, while runtime finds the actual implementation in the real object's class.