The idea: one call, two decisions
A Java call like v.treat(a) is decided twice. First javac picks
which signature to call, for example treat(Animal) or treat(Dog).
It looks only at the static types: the types the variables were declared with.
Choosing between methods with the same name and different parameters is
overload resolution. Then, while the program runs, the JVM picks
which body of that signature to run. It looks only at the class of the receiver object
v. Choosing between a method and the same method in a subclass is
overriding, or dynamic dispatch.
The page uses these four classes. Every method returns its own name, so the output shows which one ran.
class Animal {
String speak() { return "Animal.speak()"; }
static String kind() { return "Animal.kind()"; }
}
class Dog extends Animal {
@Override String speak() { return "Dog.speak()"; }
static String kind() { return "Dog.kind()"; } // hides Animal.kind()
}
class Vet {
String treat(Animal a) { return "Vet.treat(Animal)"; }
String treat(Dog d) { return "Vet.treat(Dog)"; } // an overload
}
class DogVet extends Vet {
@Override String treat(Animal a) { return "DogVet.treat(Animal)"; }
}
How to read the page
- Compile time (left): the declarations, the call, the candidate methods with ✓ or ✗, the chosen one in green, and the bytecode javac writes.
- Run time (right): the variables and the objects they point to, and each class with the methods it declares itself. The orange box is the instruction, then the signature being looked up.
- Output (bottom): each call, what javac picked and what the JVM ran.
- Pick a receiver and an argument in the dropdowns, then press
v.treat(x),x.speak()orx.kind().xstands for the argument variable,aord.
Overloading: javac picks the most specific method
Two methods are overloads when they have the same name and different parameter types. javac chooses between them in three steps (JLS §15.12.2):
- Candidates: the methods with that name in the static type of the receiver.
For
v.treat(…)withVet v, that istreat(Animal)andtreat(Dog)ofVet. - Applicable: a method applies if each argument's static type can be
converted to the parameter type. A
Dogcan be passed where anAnimalis expected; anAnimalcannot be passed where aDogis expected without a cast. - Most specific: if several apply, javac takes the one whose parameter types
are subtypes of the others'.
treat(Dog)is more specific thantreat(Animal), becauseDogis a subtype ofAnimal. If no single one is most specific, the call is a compile error ("reference to treat is ambiguous").
The object never takes part. Animal a = new Dog() holds a Dog, yet
v.treat(a) calls treat(Animal). Change only the declaration to
Dog d = new Dog() and the same object goes to treat(Dog).
(Demo: same Dog, two static types)
Applicability is tried in three phases, and javac stops at the first phase that finds a method:
| Phase | Allowed | Example: f(5) |
|---|---|---|
| 1 | subtyping and widening only (int to long) | f(long) wins over f(Integer) |
| 2 | also boxing and unboxing (int to Integer) | f(Integer) if there is no f(long) |
| 3 | also varargs | f(int...) only if nothing else applies |
The result is written into the class file as one fixed reference, such as
invokevirtual Vet.treat:(LAnimal;)Ljava/lang/String;. The part in brackets is the
descriptor: the parameter types and the return type. The JVM never redoes overload
resolution.
Overriding: the JVM looks at the receiver object
A method in a subclass overrides a method of its superclass when it has the same
name and the same parameter types. DogVet.treat(Animal) overrides
Vet.treat(Animal). To run invokevirtual Vet.treat(Animal), the JVM reads
the receiver object, takes its class, and looks for treat(Animal) there. If that class
does not declare it, the JVM tries the superclass, and so on up (JLS §15.12.4.4). Changing only the
receiver's object changes the body that runs. (Demo: the receiver picks the override)
DogVet overrides only treat(Animal). For v.treat(d) javac
picks treat(Dog), the lookup finds nothing in DogVet and goes up to
Vet. The DogVet object runs Vet.treat(Dog).
(Demo: inherited overload, no override)
Write @Override on every overriding method. If the signature does not match a
superclass method, javac stops with an error instead of quietly adding one more overload. The
classic case is boolean equals(Dog other), which overloads
equals(Object) instead of overriding it.
Overload A, override B
Put the two together. Vet v = new DogVet(); Animal a = new Dog(); v.treat(a);
- javac:
vis aVetandais anAnimal, so onlytreat(Animal)applies. It writesVet.treat(Animal). - JVM:
vholds aDogVet, which overridestreat(Animal). It runsDogVet.treat(Animal).
The Dog inside a never counted. Java looks at the run-time class of the receiver
only, not of the arguments. This is called single dispatch. Code that needs to
choose by the argument's object too uses a pattern such as Visitor, or a
switch with type patterns. (Demo: one call, two decisions)
Static methods hide, they do not override
A static method belongs to the class, not to an object. Dog.kind() has the same
signature as Animal.kind(), but it only hides it. javac compiles
a.kind() to invokestatic Animal.kind from the static type of
a, so Animal a = new Dog() prints Animal.kind(), while
a.speak() prints Dog.speak(). (Demo: static methods hide, not
override)
javac still evaluates d and throws the value away, but no object is read. So
Dog d = null; d.kind() prints Dog.kind() with no exception, while
d.speak() throws NullPointerException: an instance call needs an object
to start the lookup. (Demo: a null receiver) Calling a static method through a variable is
legal but misleading; write Dog.kind(). A null argument, on the other
hand, is just a value: v.treat(d) with Dog d = null still runs
Vet.treat(Dog). (Demo: a null argument)
Side by side
| Overloading | Overriding | |
|---|---|---|
| Methods | same name, different parameter types | same name and parameter types, in a subclass |
| Where | one class or a class and its subclass | a subclass and its superclass |
| Chosen by | javac, at compile time | the JVM, at run time |
| Looks at | static types of the receiver and the arguments | the class of the receiver object |
| Static methods | can be overloaded | cannot be overridden, only hidden |
| Also called | static or compile-time polymorphism | dynamic dispatch, run-time polymorphism |
See also C++ virtual functions: the vptr and the vtable for how a dynamic call is implemented with a table of method addresses, Inheritance vs composition for when a class tree is the right design, How a Java program is compiled and run for javac and the class file, and Lambdas and invokedynamic for the call instruction behind lambdas.
What the page leaves out
The page leaves out interfaces and default methods (invokeinterface), private methods
and constructors (never overridden), super.treat(…) calls, generics and erasure
(bridge methods), covariant return types, the access rules for overriding (an override may not be
less visible, or throw broader checked exceptions), the full rules for "most specific" with
several parameters and with lambdas, and how HotSpot speeds up the lookup with method tables and
inline caches. Object, the superclass of Vet and Animal, is
not drawn.