Method Resolution with Interfaces
What you'll learn: How Java resolves which method implementation to call when working with interface references and default methods.
When you call a method through an interface reference, Java uses dynamic dispatch to find the right implementation—but interfaces add extra complexity beyond simple class hierarchies.
Interface References and Implementation Resolution
When an object is referenced through an interface type, Java still looks at the actual object's class at runtime to find the method implementation. The interface reference only determines what methods are available at compile time—it doesn't dictate which implementation runs.
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof");
}
}
class Cat implements Animal {
public void makeSound() {
System.out.println("Meow");
}
}
Animal pet = new Dog(); // Interface reference
pet.makeSound(); // Calls Dog's implementation → "Woof"
Even though pet is declared as Animal, Java dispatches to Dog.makeSound() because that's the actual object type.
Default Methods Resolution
When interfaces provide default methods, resolution becomes more nuanced. If a class implements an interface with a default method but doesn't override it, calling that method through the interface reference executes the interface's default implementation.
interface Drawable {
default void draw() {
System.out.println("Drawing shape");
}
}
class Circle implements Drawable {
// Does not override draw()
}
Drawable shape = new Circle();
shape.draw(); // Calls Drawable's default → "Drawing shape"
The key principle: Java always searches for the most specific implementation, starting with the actual class, then moving up the hierarchy and to interfaces.
Key Takeaway: Method resolution with interfaces follows dynamic dispatch—the actual object's type determines which implementation runs, whether that's an overridden method in the class or a default method from the interface.