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.

Three boxes left to right. javac at compile time: v is a Vet and a is an Animal, so it picks the signature treat(Animal). The class file holds invokevirtual Vet.treat(Animal). The JVM at run time: v holds a DogVet object, so it runs DogVet.treat(Animal). Below javac: uses static types, chooses the overload. Below the JVM: uses the receiver object's class, chooses the override
javac fixes the signature from static types; the JVM picks the body from the receiver's class.

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() or x.kind(). x stands for the argument variable, a or d.

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):

  1. Candidates: the methods with that name in the static type of the receiver. For v.treat(…) with Vet v, that is treat(Animal) and treat(Dog) of Vet.
  2. Applicable: a method applies if each argument's static type can be converted to the parameter type. A Dog can be passed where an Animal is expected; an Animal cannot be passed where a Dog is expected without a cast.
  3. Most specific: if several apply, javac takes the one whose parameter types are subtypes of the others'. treat(Dog) is more specific than treat(Animal), because Dog is a subtype of Animal. 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:

PhaseAllowedExample: f(5)
1subtyping and widening only (int to long)f(long) wins over f(Integer)
2also boxing and unboxing (int to Integer)f(Integer) if there is no f(long)
3also varargsf(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: v is a Vet and a is an Animal, so only treat(Animal) applies. It writes Vet.treat(Animal).
  • JVM: v holds a DogVet, which overrides treat(Animal). It runs DogVet.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)

A grid. Rows: the receiver object, a Vet or a DogVet. Columns: the argument declared as Animal a = new Dog() or as Dog d = new Dog(). Cells: Vet with Animal gives Vet.treat(Animal); Vet with Dog gives Vet.treat(Dog); DogVet with Animal gives DogVet.treat(Animal); DogVet with Dog gives Vet.treat(Dog). The column picks the overload, the row picks the override
The argument's declared type picks the column (the overload); the receiver object picks the row (the override).

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

OverloadingOverriding
Methodssame name, different parameter typessame name and parameter types, in a subclass
Whereone class or a class and its subclassa subclass and its superclass
Chosen byjavac, at compile timethe JVM, at run time
Looks atstatic types of the receiver and the argumentsthe class of the receiver object
Static methodscan be overloadedcannot be overridden, only hidden
Also calledstatic or compile-time polymorphismdynamic 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.

On the mind map

Open the Software Design mind mapSoftware DesignPrinciples: keep each change localPrinciplesDesign patterns: named fixes for common designsDesign patternsArchitecture: the shape of a whole appArchitectureEnterprise app patterns: logic, SQL, locks, money (PoEAA)Enterprise app patternsGit storage: content named by its hashGit storageGit branches & merging: pointers to commits, then mergeGit branches & mergingTesting: check code in isolationTestingSOLIDSOLIDfive rules so one change hits one classInheritance vs compositionInheritance vs compositionis-a locks the tree; has-a mixes partsVirtual calls, vtableVirtual calls, vtableobject → vptr → vtable slot → functionOverloading vs overridingjavac: static types; JVM: receiver's classCoupling and cohesionCoupling and cohesionOne change should touch one moduleControl-flow coverageControl-flow coverage100% statements can still miss a bugBoundary Value TestingBoundary Value TestingBugs sit at class edges: test min−1 … max+1Condition Coverage and MC/DCCondition Coverage and MC/DCEach condition flips D alone: N+1 testsMutation testingMutation testingCoverage runs code; mutants test the assertsOpen the Software Design mind mapSoftware Designkeep each change localPrinciplesSOLIDSOLIDfive rules so one change hits one classInheritance vs compositionInheritance vs compositionis-a locks the tree; has-a mixes partsVirtual calls, vtableVirtual calls, vtableobject → vptr → vtable slot → functionOverloading vs overridingjavac: static types; JVM: receiver's classCoupling and cohesionCoupling and cohesionOne change should touch one moduleControl-flow coverageControl-flow coverage100% statements can still miss a bugBoundary Value TestingBoundary Value TestingBugs sit at class edges: test min−1 … max+1Condition Coverage and MC/DCCondition Coverage and MC/DCEach condition flips D alone: N+1 testsMutation testingMutation testingCoverage runs code; mutants test the asserts
This page on the Software Design mind map · 38 pages in 7 branches · open it to see the whole map and test yourself in recall mode.