Object-Oriented Programming with Java · Lecture Notes

Chapter 4.4: Polymorphism

In a zoo, the keeper says “everybody make a sound”; the dog barks and the cat meows. The keeper does not give each animal a separate command; every animal answers the same command in its own way. In object-oriented programming this idea is called polymorphism. The code is written once against the superclass type; at run time each object answers the call with its own version. These notes first establish the difference between the reference type and the object type: the compiler looks at one, the Java virtual machine (JVM) at the other. Upcasting and downcasting, ClassCastException and the instanceof test follow. Dynamic binding, method lookup and the method table are at the center of the notes. Why fields, static methods and overloading are resolved at compile time is examined separately. The notes end with a shape hierarchy, polymorphic parameters, an anti-tank game, and the symmetry trap of the equals method.

Learning outcomes

Concept
Define polymorphism; tell compile-time polymorphism from run-time polymorphism.
Reference rule
Explain why a subclass object can be assigned to a superclass reference and why the reverse is a compile error.
Type conversion
Write upcasts and downcasts; prevent ClassCastException with instanceof; recognize the ArrayStoreException that array covariance causes.
Dynamic binding
Trace step by step how the method to call is chosen by the actual class of the object; show method lookup in the hierarchy and in the method table.
Overloading and overriding
Compare overloading and overriding; know which one the compiler chooses and which one the JVM chooses; apply the three phases of overload resolution.
Design
Write general code against the superclass type, using the shape array and the anti-tank game as examples; recognize the symmetry trap of the equals method.

4.4.1The concept of polymorphism

The four basic principles of object-oriented programming are encapsulation, inheritance, polymorphism and abstraction. Encapsulation gathers data and the methods that work on it in one class. Inheritance lets a class extend another class. Polymorphism is built on these two: without a class hierarchy there is no run-time polymorphism either. That is why the basic concepts of inheritance are used here too: superclass, subclass, extends, overriding and @Override.

4.4.1.1What is polymorphism?

Definition 4.4.1

Polymorphism means that the same expression leads to different behavior in different objects. The word comes from the Greek poly (many) and morph (form). In Java, a reference can refer to an object of its own type or of one of its subclasses. Which version of an overridden method called through this reference runs is determined by the actual class of the object it refers to.

The core of the definition can be seen in a single line. The call animal.makeSound() prints Woof woof! if animal refers to a dog and Meow! if it refers to a cat. The line is the same; the behavior changes with the object. The code is written once with the superclass type; each object answers the call with its own version.

Everyday life has many examples of this idea. The same “on” button on a remote control turns on the television, the air conditioner and the projector; each device does the job in its own way. With a class B driving licence you can drive any make of car. The driver uses only the “car” interface: steering wheel, pedals, gears. The details of the engine belong to the make. The keeper at the zoo also gives a single command and every animal makes its own sound. In all three examples the caller knows a common interface; the object completes the details itself.

Animal h1 = new Dog();
Animal h2 = new Cat();

h1.makeSound(); // Woof woof!
h2.makeSound(); // Meow!

In these four lines both variables have type Animal. h1 refers to a Dog and h2 to a Cat. The compiler compiles both calls in the same way, as a call to the method makeSound() of class Animal. When the program runs, the JVM looks at the object at each call and runs the version of Dog for the dog and that of Cat for the cat. The output is as written in the comments of the code: first Woof woof!, then Meow!.

4.4.1.2Two kinds of polymorphism

In Java, “same name, different behavior” is obtained by two different mechanisms. The first is overloading: several methods with the same name but different parameters are written in the same class. The compiler decides which one to call. The second is overriding: a subclass rewrites a method it took from the superclass with the same signature. The JVM decides which version runs while the program is running.

Definition 4.4.2

Compile-time polymorphism (static polymorphism) means that the compiler chooses among overloaded methods by looking at the number and declared types of the arguments. Run-time polymorphism (dynamic polymorphism) means that the choice among overridden methods is made while the program runs, by looking at the actual class of the object. This second choice is called dynamic binding.

The two kinds can be seen side by side in the two short examples below. In the example on the left there are two add methods in a single class; if the arguments are integers the int version is chosen, if they are decimal the double version. This choice is made while the program is compiled and is written into the bytecode. In the example on the right the choice depends on the object and becomes known only while the program runs.

int add(int a, int b) { ... }
double add(double a, double b) { ... }

add(5, 3);     // int version
add(3.5, 2.7); // double version
Table 4.4.1: Comparison of the two kinds of polymorphism.
Compile time (static)Run time (dynamic)
MechanismOverloadingOverriding + dynamic binding
Who choosesThe compiler (javac)The JVM, while the program runs
What is looked at?The number and declared types of the argumentsThe actual class of the object
Is inheritance needed?No, it works within a single classYes, a class hierarchy is needed
In shortSame name, different parametersSame signature, different classes

In everyday conversation, “polymorphism” usually means run-time polymorphism. Most of these notes are about it. Overloading is also examined separately, because the two mechanisms can work together in the same call, and this is where most of the confusion arises.

4.4.1.3The example class hierarchy

Most of these notes use the same small hierarchy. Class Animal has three methods: makeSound(), run() and sleep(). Dog and Cat derive from this class. Like every class, Animal derives from Object, the ancestor of all classes in Java. Figure 4.4.1 shows this structure as a UML class diagram.

class Animal {
  public void makeSound() { System.out.println("Animal sound"); }
  public void run()      { System.out.println("Animal runs"); }
  public void sleep()      { System.out.println("Animal sleeps"); }
}
class Dog extends Animal {
  @Override public void makeSound() { System.out.println("Woof woof!"); }
  @Override public void run() { System.out.println("Dog runs"); }
  public void bark() { System.out.println("Dog barks"); }
}
class Cat extends Animal {
  @Override public void makeSound() { System.out.println("Meow!"); }
  public void scratch() { System.out.println("Cat scratches"); }
}
Object+toString(): String+equals(Object): boolean+getClass(): ClassAnimal+makeSound(): void+run(): void+sleep(): voidDog+makeSound(): void+run(): void+bark(): voidCat+makeSound(): void+scratch(): void
Figure 4.4.1: The example class hierarchy. Dog and Cat derive from Animal; Animal derives from Object. The arrows point from the subclass to the superclass.

The two subclasses relate to the superclass differently. Dog overrides makeSound() and run() and adds its own bark() method. Cat overrides only makeSound() and adds scratch(). Neither subclass overrides sleep(); both take it from Animal as it is. run() has changed only in the dog; the cat uses the version of Animal.

Each of these details corresponds to a rule. bark() exists only in Dog, so it cannot be called through a reference of type Animal. Since sleep() is not written in the subclasses, the method lookup climbs up to Animal. The @Override annotation tells the compiler that “this method overrides a method in the superclass”. If the name or a parameter is misspelled, the compiler reports an error.

The is-a relationship of inheritance is the basis of all the rules here. A dog and a cat are both animals. That is why both can be held in a variable of type Animal. The reverse is not true: not every animal is a dog.

4.4.2References and type compatibility

To understand polymorphism, first remember that variables in Java hold not the object but a reference to it. The object lives on the heap. The variable sits in a frame on the stack and points to the location of the object on the heap. Many references can point to one object, and the types of these references can differ.

4.4.2.1One object, three references

The code below creates a single Dog object and refers to it with references of three different types.

// reference to a Dog object
Dog dog = new Dog();
// an Animal reference can point to a Dog
Animal animal = dog;
// so can an Object reference
Object obj = animal;
System.out.println(dog == animal);
System.out.println(animal == obj);
System.out.println(obj.getClass());

The program prints:

true
true
class Dog

Let us follow the code line by line. The new Dog() in the first line creates an object on the heap. The reference dog points to this object; the type of the reference is Dog. The second assignment does not create a new object. animal is a second reference that points to the same object. The assignment is valid, because a dog is an animal. In the third assignment, obj of type Object also points to the same object. Since every class derives from Object, this is valid too.

The next two lines use the == operator. For reference types, == compares not the contents of the objects but whether the references point to the same object. Since all three references point to the same object, both comparisons give true. The getClass() in the last line returns the run-time class of the object. Even though the type of the reference is Object, the class of the object has not changed: class Dog.

Reference variablesobject on the heapdogtype: Doganimaltype: Animalobjtype: ObjectDog objectObject partAnimal partDog part
Figure 4.4.2: Three references, one object. dog, animal and obj point to the same Dog object on the heap. Inside the object are the parts that come from Object, Animal and Dog.

Figure 4.4.2 also shows the internal structure of the object. A Dog object carries the parts from every class in the inheritance chain: the Object part, the Animal part and the Dog part. That is why the object can be referred to by a reference of any type in the chain. Each reference points to the whole object, but sees the object through the window of its own type.

4.4.2.2Reference type and object type

The previous example shows that every reference variable has two separate types. One is the type written in the variable's declaration. The other is the class of the object the variable currently refers to.

Definition 4.4.3

The declared type of a reference variable is the type written in its declaration and does not change during the variable's lifetime. Its actual type is the class of the object the variable currently refers to, and it can change with assignment. The declared type is also called the reference type, and the actual type the object type.

Animal h = new Dog();
// declared type: Animal
// actual type:   Dog
Animal hreferenceDog objecton the heapdeclared typecompiler looksactual typeJVM looks
Figure 4.4.3: The two types of the line Animal h = new Dog();. The declared type is Animal and the compiler looks at it. The actual type is Dog and the JVM looks at it.

The two types have different functions, and this distinction is the key to the rest of the notes. The compiler checks the code before the program runs. At that moment no object exists; the compiler knows only the declarations of the variables. So all of the compiler's decisions rest on the declared type. The JVM, while the program runs, meets the real object and knows which class it belongs to. Table 4.4.2 summarizes three basic questions and who answers them.

Table 4.4.2: Reference type and object type: who decides which question?
QuestionWho decides?
Can this method be called?The compiler, by looking at the reference type.
Which version runs?The JVM, by looking at the object type.
Which assignments are valid?The compiler, by looking at the reference type.

The result of the first question can be seen in the code below. The object really is a dog, but the type of the variable is Animal.

Animal animal = new Dog();
animal.bark(); // compile error
error: cannot find symbol
  symbol:   method bark()
  location: variable animal of type Animal

When the compiler reaches the line animal.bark(), it knows only this: animal is a variable of type Animal. There is no method called bark() in class Animal or in its superclass Object. The compiler cannot know which object the variable refers to. When the program reaches that line, the variable may be pointing at a cat. That is why it does not allow the call. The line location: variable animal of type Animal in the message also says plainly that the decision was made by the type of the variable.

The remote control analogy describes this well. The reference type is a remote control; only the buttons the remote has can be used. Even if the object is a dog, the Animal remote has no bark() button. What the device does when a button is pressed is determined by the device, that is, the object. The makeSound() button is on the Animal remote; if the object is a dog, a bark is heard when it is pressed, if a cat, a meow.

Common mistake

Thinking “the object is a dog, so bark() can be called”. Whether a call compiles is decided not by the object but by the declared type of the reference. If bark() is to be called, the reference is either declared as Dog from the start or converted to Dog by a downcast.

4.4.2.3The reference rule

The validity of assignments is also checked against the declared types. Java's rule on this is short and comes from the is-a relationship of inheritance.

Definition 4.4.4

The reference rule: An object of a subclass can be assigned to a reference of the superclass type. An object of the superclass cannot be assigned to a reference of a subclass type. In short, assignment from a subclass reference to a superclass reference is automatic; the reverse needs an explicit cast.

// Dog is a subtype of Animal
Animal animal = new Dog();
Object obj = new Cat();

These two assignments are valid. Every dog is an animal: a dog can do everything expected of an animal, that is, makeSound(), run() and sleep(). Every cat is an Object too. A reference of a supertype cannot ask for anything the object of the subtype cannot do. That is why the assignment is safe.

// Animal is Dog's superclass
Dog dog = new Animal();
error: incompatible types:
  Animal cannot be converted to Dog

This assignment, however, does not compile. Through the variable dog, dog.bark() could be called later. A plain Animal object does not know bark(). Had the compiler allowed such an assignment, the program would try to call a nonexistent method at run time. Java prevents this kind of error up front, at compile time.

Animal hDog object✓ validDog kAnimal object✗ does not compile
Figure 4.4.4: The reference rule. An Animal reference can point to a Dog object; a Dog reference cannot point to an Animal object.

The most surprising consequence of the rule can be seen in these two lines:

Animal h = new Dog();
Dog k = h;   // compile error
error: incompatible types: Animal cannot be converted to Dog

Here the object that h points to really is a dog. Even so, the second line does not compile, and the same message appears. The compiler sees not the object h points to but only its declared type (Animal). It does not read the previous line and conclude “so this is a dog”; it could not do that in every case anyway. The solution is an explicit cast: Dog k = (Dog) h;. With this notation the programmer tells the compiler “I am sure this reference points to a dog”. Whether the cast is correct is checked at run time.

Example 4.4.1

Dog and Cat derive from Animal. Which of the following four assignments compile?

(a) Animal h = new Cat(); — Compiles. A cat is an animal; a subclass object is assigned to a superclass reference.

(b) Object o = new Dog(); — Compiles. Every class is a subclass of Object.

(c) Cat c = new Dog(); — Does not compile: incompatible types: Dog cannot be converted to Cat. Dog and Cat are sibling classes; there is no is-a relationship between them.

(d) Dog k = new Animal(); — Does not compile: incompatible types: Animal cannot be converted to Dog. A superclass object cannot be assigned to a subclass reference.

4.4.3Type conversion

Conversion is a familiar operation with primitive types. Going from int to double happens by itself; (int) 3.7 is an explicit cast and changes the value. With reference types there are two similar directions, but with an important difference: a reference conversion never changes the object. Only the type of the reference looking at the object changes.

4.4.3.1Upcasting and downcasting

Definition 4.4.5

Upcasting is converting a reference of a subclass type to a superclass type. It is automatic and always safe. Downcasting is converting a reference of a superclass type to a subclass type. It is done explicitly by writing the target type in parentheses: (Dog) h. Its success depends on the object the reference points to.

AnimalDogupautomaticdownwith (Dog)
Figure 4.4.5: Upcasting from Dog to Animal happens by itself. Downcasting from Animal to Dog is done with an explicit cast, by writing (Dog).
Dog dog = new Dog();
Animal h = dog;    // up: automatic
Animal h1 = (Animal) dog; // unnecessary

On the second line the upcast is done by itself; it is the reference rule itself. The (Animal) on the third line is valid too, but unnecessary. The compiler does this conversion itself anyway.

Animal h = new Dog();
Dog k = (Dog) h; // down: explicit
k.bark();           // Dog barks

Here we go in the opposite direction. The declared type of h is Animal; the type of the expression (Dog) h is Dog. This expression can be assigned to k of type Dog, and k.bark() compiles. While the program runs, the JVM checks whether the object h points to really is a Dog. Since the object is a dog, the cast succeeds and Dog barks is printed.

Table 4.4.3: Comparison of upcasting and downcasting.
UpcastingDowncasting
DirectionSub → superSuper → sub
NotationAutomatic (implicit)Explicit: (Dog) h
Safe?AlwaysDepends on the object
Other nameWidening conversionNarrowing conversion

The names “widening” and “narrowing” in the table are familiar from primitive types. The Java Language Specification uses these names for reference conversions too. An upcast counts as “widening” even though it narrows the set of methods the reference can see. The name comes from the widening of the set of objects the type covers: the type Animal covers all dogs, cats and other animals.

Common mistake

Thinking “a cast changes the object”. Writing (Animal) dog does not turn the dog into a plain animal. The call ((Animal) dog).makeSound() still prints Woof woof!, because the object decides which version runs. A cast changes only the type in which the compiler sees that expression.

4.4.3.2Downcasting and the precedence trap

The purpose of downcasting is to call methods that are not in the superclass and belong only to the subclass. A superclass reference can be assigned to a subclass variable only through this cast. The cast is written in two forms: its result is assigned to a variable, or it is used directly on the same line.

Animal h2 = new Dog();
Dog k = (Dog) h2;
k.bark();
((Dog) h2).bark(); // in one line
Dog barks
Dog barks

The program prints Dog barks twice. In the first form the result of the cast is assigned to k and k.bark() is called. In the second, the expression ((Dog) h2) produces a Dog reference and .bark() is applied directly to it. The outer pair of parentheses is mandatory. The reason is operator precedence in Java.

Definition 4.4.6

The precedence rule: Member access and method call (.) are applied before the cast operator. The expression (Dog) h2.bark() is read as (Dog) (h2.bark()): the cast is meant to apply to the result of the method call.

(Dog) h2.bark();   // wrong
error: not a statement

When the compiler parses this line, it sees first the call h2.bark(), then the conversion of its result to Dog. Such a cast expression cannot be a statement on its own; the compiler says not a statement. Even if the line is fixed in some other way, a second problem remains: the declared type of h2 is Animal, and Animal has no bark().

When the expression is used on the right of an assignment, the second problem shows directly:

String s = (Dog) h2.name();
// h2.name() first → not in Animal
error: cannot find symbol
  symbol:   method name()
  location: variable h2 of type Animal

Here too the compiler first tries to resolve h2.name(). It cannot find name() in class Animal and reports an error. For this line, javac of JDK 21 also gives a second message: incompatible types: Dog cannot be converted to String. The result of the cast is a Dog and cannot be assigned to a String variable. The correct form is always the same: the cast is put in parentheses and the dot is written outside the parentheses: ((Dog) h2).bark();.

4.4.3.3ClassCastException

A downcast is a promise given to the compiler. The compiler cannot know whether the promise is true and accepts it. If the promise is not kept, the error appears while the program runs.

Animal h4 = new Cat();
Dog k4 = (Dog) h4; // compiles!
k4.bark();
Exception in thread "main" java.lang.ClassCastException:
class Cat cannot be cast to class Dog

The second line compiles. From the compiler's point of view there is no problem in it: a reference of type Animal may well be pointing at a Dog. When the program runs, the JVM checks the actual class of the object at the moment of the cast. The object is a Cat, and a cat is not a dog. In this case the JVM throws ClassCastException; since nobody catches it, the program stops. The third line never runs.

Definition 4.4.7

ClassCastException is the run-time exception the JVM throws when a reference is explicitly cast to a type that is incompatible with the class of the object it points to. The cast (T) r succeeds only if the object r points to is an instance of T or of a subclass of T. If r is null, the cast always succeeds and the result is null again.

In JDK 21 the whole message is a little longer: class Cat cannot be cast to class Dog (Cat and Dog are in unnamed module of loader 'app'). The part in parentheses says from which module and class loader the classes come; it is not important in this course. The first part of the message tells everything: which class was asked to be cast to which class.

The same exception appears when a plain superclass object is cast to a subclass:

Dog k5 = (Dog) new Animal(); // compiles!
java.lang.ClassCastException:
class Animal cannot be cast to class Dog

This line compiles too, because the type of the expression is Animal and a cast from Animal to Dog is possible in the compiler's eyes. But the object that was created is not a dog and never will be. The general conclusion is this: an object of the superclass itself can never be assigned to a subclass reference. The cast succeeds only if the object really is of that subclass.

There is also a kind of cast the compiler does not accept at all. If a cast is written between two types that have no inheritance relationship, the compiler knows it cannot be right for any object:

Dog dog = new Dog();
Cat c = (Cat) dog;   // compile error
error: incompatible types: Dog cannot be converted to Cat

Dog and Cat are sibling classes. An object cannot be both a dog and a cat at the same time; in Java a class has only one superclass. So the compiler rejects the cast at compile time. For classes the rule is briefly this: a cast does not compile if neither the source type nor the target type is a subtype of the other; if one is a subtype, it compiles and is checked at run time.

Example 4.4.2

Given Animal h4 = new Cat();. What are the decisions of the compiler and the JVM for the following three casts?

(a) (Cat) h4: Cat is a subtype of Animal; it compiles. The object is a cat; the JVM approves. Succeeds.

(b) (Dog) h4: Dog is a subtype of Animal; it compiles. The object is a cat; the JVM throws ClassCastException.

(c) (Object) h4: it is an upcast, compiles and always succeeds. The object does not change; the type of the reference becomes Object.

4.4.3.4Code trace: a faulty downcast

The program below contains one successful and one failing downcast. The trace is easier to read if the lines are numbered from 1 to 7.

Animal h1 = new Dog();
Animal h2 = new Cat();
Dog k1 = (Dog) h1;
k1.bark();
Dog k2 = (Dog) h2;
k2.bark();
System.out.println("Done");
Table 4.4.4: Trace of the faulty downcast program.
LineCompilerJVM (at run time)State / output
1Upcast, validDog object #1 is createdh1 → #1
2Upcast, validCat object #2 is createdh2 → #2
3Animal → Dog possible, compilesIs #1 a Dog? Yesk1 → #1
4Dog has bark()Dog.bark()Dog barks
5Animal → Dog possible, compilesIs #2 a Dog? Cat → Animal → Object: noClassCastException, nothing is assigned to k2
6CompilesDoes not run—
7CompilesDoes not runDone is not printed
StackHeapmain()h1h2k1k2?Dog #1Cat #2JVM check: is Cat a Dog?CatAnimalObject ✗
Figure 4.4.6: The JVM's check at line 5. In the chain going up from the class of the object h2 points to (Cat → Animal → Object) there is no Dog; the cast fails and k2 stays empty.

The most important row of the table is line 5. The compiler cannot tell this line apart from line 3; in both the declared type is Animal and the target type is Dog. The difference shows only at run time, when the object is looked at. The JVM's check is the chain walk seen in Figure 4.4.6: it starts at the class of the object and walks up the superclasses looking for Dog. If no Dog is found up to Object, the cast is rejected.

The output of the program is only the line Dog barks, followed by the exception message. Done is not printed, because when an exception is not caught, the main method ends on the spot.

4.4.3.5Safe casting with instanceof

If it is not known in advance what class of object a reference points to, a test is made before the downcast. Java offers the instanceof operator for this.

Definition 4.4.8

The expression reference instanceof Type gives true if the object the reference points to is of Type or of one of its subclasses, and false otherwise. null instanceof Type is always false. If there is no inheritance relationship at all between the declared type of the reference and Type, the expression does not compile.

The loop below tests the type first and then casts, for each element of the array animals = {new Dog(), new Cat(), new Animal()}.

for (Animal x : animals) {
    if (x instanceof Dog) {
        Dog kk = (Dog) x;
        kk.bark();
    } else if (x instanceof Cat) {
        ((Cat) x).scratch();
    } else {
        System.out.println("No special behavior");
    }
}
Dog barks
Cat scratches
No special behavior

Since the test comes first and the cast second, ClassCastException cannot occur. If x instanceof Dog is true, the object x points to is certainly a dog and (Dog) x succeeds. The third element is a plain Animal; both tests come out false and the else branch runs.

The order of the tests matters too. instanceof includes subclasses. The test x instanceof Animal gives true for both a dog and a cat. That is why in a chain the lowest, most specific classes are tested first. If the order is reversed, the general branch catches every object and the specific branches never get their turn.

Pattern matching, which came with Java 16, shortens this idiom. If the test is true, the cast value is bound directly to a new variable:

if (x instanceof Dog kk) {
    kk.bark(); // the cast is automatic
}

The variable kk is defined only in the true branch of the if and has type Dog. The compiler writes the cast; the programmer need not write (Dog) x separately. Since the test and the cast are not on separate lines, a mistake like changing one and forgetting the other cannot be made either.

The way the tests work in each round is clearer if a version of the same loop with the elements in a different order is traced.

Animal[] arr = {new Cat(), new Animal(), new Dog()};
for (Animal x : arr) {
    if (x instanceof Dog) {
        ((Dog) x).bark();
    } else if (x instanceof Cat) {
        ((Cat) x).scratch();
    } else {
        System.out.println("No special behavior");
    }
}
Table 4.4.5: Trace of the instanceof chain. Array: {Cat, Animal, Dog}.
Roundx → objectinstanceof Doginstanceof CatBranch that runsOutput
1Cat #1falsetrue((Cat) x).scratch()Cat scratches
2Animal #2falsefalseelseNo special behavior
3Dog #3true— (not tested)((Dog) x).bark()Dog barks
arr•••Cat #1Animal #2Dog #3x→ Cat #1x instanceof Dogfalsex instanceof Cattrue
Figure 4.4.7: The first round. x points to a Cat; the Dog test is false and the Cat test is true. Since it was tested first, the cast (Cat) x is safe.

In the second round there is a plain Animal object. This object is an instance of no subclass; both tests come out false. In the else branch no cast is attempted, so there is no risk of an error. In the third round the first test is true; the next condition in the else if chain is not tested. In none of the three rounds does ClassCastException occur.

Long instanceof chains are often a design warning. When a new subclass is added (for example Bird), a new branch has to be added to the chain; if it is forgotten, the bird silently falls into the else branch. A better solution is to move the behavior into a method defined in the superclass and overridden in the subclasses.

4.4.3.6Arrays and ArrayStoreException

The reference rule applies to arrays too. Since Dog is an Animal, a Dog[] counts as an Animal[] as well. This property of Java arrays is called covariance.

Definition 4.4.9

Arrays are covariant: if A is a subtype of B, then A[] is a subtype of B[]. So a Dog[] object can be assigned to an Animal[] reference. The array object, however, knows its own actual element type. Every element written into the array is checked against this type at run time; for an element that does not fit, ArrayStoreException is thrown.

Dog[] dogs = new Dog[2];
Animal[] animals = dogs;   // compiles
animals[0] = new Dog();
System.out.println("first ok");
animals[1] = new Cat();       // compiles, but...
System.out.println("never reached");
first ok
Exception in thread "main" java.lang.ArrayStoreException: Cat

On the second line an upcast is done and it compiles. The array object is really a Dog[]; animals is a second reference that only looks at it. On the third line a dog is written into the array; the JVM's check passes and first ok is printed. On the fifth line animals[1] = new Cat(); is valid in the compiler's eyes: an Animal is written into an array of type Animal[]. But the JVM looks at the actual element type of the array at the moment of writing. A cat cannot be put into a Dog[] array; ArrayStoreException: Cat is thrown and the last line does not run.

This is a known gap in the type safety of arrays. The JVM catches an error the compiler could not catch with the check it makes at every write. Reading is safe: every element read from a Dog[] array is an Animal. The problem arises only when writing.

Generic collections close the same gap at compile time. List<Dog> is not a subtype of List<Animal>:

List<Animal> l = new ArrayList<Dog>();
error: incompatible types: ArrayList<Dog>
  cannot be converted to List<Animal>

Had the compiler allowed this assignment, a cat could be added to the list with l.add(new Cat()). Since generic type information is not kept at run time, the JVM could not catch it. That is why Java does not make generics covariant and turns the problem into a compile error up front.

Common mistake

Relying on array covariance: Animal[] d = new Dog[2]; d[1] = new Cat(); compiles, but at run time gives ArrayStoreException: Cat. An array that will hold objects of different subclasses is created with the superclass type from the start: new Animal[2].

4.4.4Dynamic binding

Matching a method call with the method body that will run is called binding. This matching can be done at two times. If it is done during compilation, it is called static (early) binding; if it is done while the program runs, dynamic (late) binding. In Java, instance methods that can be overridden are bound dynamically, and this is what makes polymorphism possible.

4.4.4.1The compiler asks “is there one?”, the JVM asks “which one?”

Definition 4.4.10

Dynamic binding is choosing the method version to call not by the declared type of the variable but by the actual class of the object, at run time. If the reference points to a subclass object and the subclass has overridden the method, the subclass's version runs.

Animal h = new Dog();
h.run();      // Dog's method
h.makeSound(); // Dog's method
h.sleep();      // not in Dog → Animal's
Dog runs
Woof woof!
Animal sleeps

All three calls are made through h, of type Animal. For h.run() and h.makeSound() the versions of Dog run, because the object is a dog and these two methods are overridden in Dog. For h.sleep() the version of Animal runs. Dog has not overridden sleep(); the version it received by inheritance is that of Animal.

Each call is resolved in two phases. Figure 4.4.8 shows these two phases for h.run().

h.run()Compiler: does Animal have run()?yes → compiles (error otherwise)JVM: which class is obj?Dog → Dog.run() runs
Figure 4.4.8: The two phases of the call h.run(). The compiler checks whether Animal has run(); the JVM looks at the class of the object and runs Dog.run().
  1. Compile time. The compiler looks at the declared type of h (Animal) and asks “does Animal have run()?” If it does, the call compiles; if not, a compile error is reported. At this phase the body to run is not chosen; only the validity of the call is settled.
  2. Run time. The JVM looks at the object h points to and asks “which run() applies in the class of this object?” The actual class is Dog; Dog.run() runs.

The rule can be summed up briefly: the compiler asks “is there one?”, the JVM asks “which one?” The compiler's approval guarantees that at least one version will be found at run time. Because whichever subclass object h points to, that class has either inherited or overridden the run() method of Animal.

4.4.4.2Method lookup from the bottom up

How the JVM answers the “which one?” question is easiest to show on the class hierarchy. The search always starts at the bottom, at the actual class of the object. If the method is found there, the search ends. If not, it moves up to the class above. This walk can continue up to Object.

Animal h = new Dog();
h.run();
h.sleep();
System.out.println(h.toString());
// h.bark(); → compile error
Object+toString(): String+equals(Object): booleanAnimal+makeSound(): void+run(): void+sleep(): void✓ foundDog+makeSound(): void+run(): void+bark(): void✗ none, go up
Figure 4.4.9: Method lookup for h.sleep(). The object is a Dog; Dog has no sleep(). The search moves one level up and ends at Animal.

Each of the four lines in the program shows a different situation:

  • h.run(): the search starts at Dog. run() is there; the search ends and Dog runs is printed.
  • h.sleep(): Dog has no sleep(). The search moves up and finds the method in Animal: Animal sleeps (Figure 4.4.9).
  • h.toString(): it is in neither Dog nor Animal. The search climbs to the very top, to Object. The toString() of Object concatenates the class name, the @ sign and a hexadecimal number (the hash code of the object); for example Dog@13221655. The number changes from run to run (Figure 4.4.10).
  • h.bark(): does not compile. This time the compiler does the search, starting from the reference type Animal. bark() is not found in Animal or in Object. Dog is never looked at, because the compiler does not go down.
Object+toString(): String+equals(Object): boolean✓ foundAnimal+makeSound(): void+run(): void+sleep(): void✗ noneDog+makeSound(): void+run(): void+bark(): void✗ none
Figure 4.4.10: Method lookup for h.toString(). A method found neither in Dog nor in Animal is found in Object at the top of the chain.

The last item shows the difference between the two searches clearly. The compiler's search starts at the reference type and goes only up. The JVM's search starts at the class of the object and also goes only up. The point where the JVM starts is lower than or at the same place as the compiler's. That is why every method the compiler finds, the JVM finds too; perhaps an overridden version of it, lower down.

Example 4.4.3

For Animal c = new Cat();, which refers to a Cat object, where does the search end for the calls c.makeSound(), c.run() and c.sleep()?

c.makeSound(): the search starts at Cat and ends there, because Cat overrides this method: Meow!.

c.run(): Cat has no run(); the search ends at Animal: Animal runs. The same call on a dog prints Dog runs.

c.sleep(): ends at Animal again: Animal sleeps.

4.4.4.3Code trace: a polymorphic array

The place where polymorphism is used most is an array or list of the superclass type. The elements of the array refer to objects of different subclasses; a single loop makes the same call on all of them.

Animal[] animals = new Animal[3];
animals[0] = new Dog();
animals[1] = new Cat();
animals[2] = new Animal();
for (int i = 0; i < animals.length; i++) {
    animals[i].makeSound();
}

The first line creates an array of three elements of type Animal. The elements are references, not objects, and at first all are null. The next three assignments bind a different object to each element. Element 0 points to a Dog, element 1 to a Cat; element 2 is a plain Animal. At every assignment an upcast is done automatically. The array now holds three different forms.

animalsheap0Dog object1Cat object2Animal object
Figure 4.4.11: The first round of the loop. animals[0] points to a Dog object; the JVM runs Dog.makeSound().
Table 4.4.6: Trace of the polymorphic array loop.
ii < animals.lengthanimals[i] → objectVersion that runsOutput
00 < 3 trueDogDog.makeSound()Woof woof!
11 < 3 trueCatCat.makeSound()Meow!
22 < 3 trueAnimalAnimal.makeSound()Animal sound
33 < 3 false——loop ends

The line animals[i].makeSound() in the loop body is the same in all three rounds. The compiler compiles this line once, as a call to Animal.makeSound(). The JVM looks at the class of the object in every round and chooses a different body. One line of code produces three different behaviors. If a Bird object were added to the array tomorrow, no change would be needed in the loop; the makeSound() version of Bird would run by itself.

Common mistake

Calling through the array before assigning objects to its elements. new Animal[3] does not create three animals; it creates three empty references. If animals[0].makeSound() is called without assignment, the program stops with NullPointerException.

4.4.4.4Behind the scenes: the method table

Searching from the bottom of the hierarchy upward is a good model for understanding dynamic binding. JVMs, however, do not walk through the classes one by one at every call; that would be slow. In reality the lookup work is largely done once, while the class is loaded.

Definition 4.4.11

The method table (virtual method table) is a table the JVM uses in dynamic binding, kept once per class. Every method that can be overridden has a fixed sequence number in the table, its slot. The slot holds the address of the method body that runs on objects of that class.

Tables are built along inheritance like this. The table of a subclass starts as a copy of the superclass's table. The slots of overridden methods get the new body. New methods added by the subclass are appended to the end of the table. So the slot number of a method stays the same in all subclasses. Figure 4.4.12 shows the tables of the example hierarchy.

Animal table[0] makeSoundAnimal[1] runAnimal[2] sleepAnimalDog table[0] makeSoundDog[1] runDog[2] sleepAnimal[3] barkDogCat table[0] makeSoundCat[1] runAnimal[2] sleepAnimal[3] scratchCatright column: the classwhere the method body is foundhighlighted name: body is written in thisclassfaded name: copied from above
Figure 4.4.12: Method tables of the classes Animal, Dog and Cat. The right column is the class where the method body is found. A highlighted name means the body is written in that class; a faded name means it was copied from the superclass.

The tables in the figure are simplified. Real tables start with the overridable methods of Object (such as toString, equals, hashCode) and slot numbers vary with the JVM. The principle is the same. In the Dog table, slots 0 and 1 (makeSound, run) point to the bodies of Dog. Slot 2, sleep, is copied from Animal. bark is appended at the end. In the Cat table only makeSound has changed, and scratch is appended at the end.

The bytecode the compiler produces uses this structure. The two lines below are taken from the output of the command javap -c Main. This command shows the bytecode of a compiled class in readable form.

47: invokevirtual #15  // Method Animal.run:()V
52: invokevirtual #18  // Method Animal.makeSound:()V

In both lines the compiler wrote only Animal.run and Animal.makeSound, because it did its check by the reference type. The names Dog and Cat do not appear in the bytecode. Which body will run is decided by the invokevirtual instruction. When this instruction runs, the JVM follows this path: reference → object → class of the object → the relevant slot in that class's table → body. The lookup is a single array access; there is no need to walk up the hierarchy.

Not all calls are made with invokevirtual. Constructors and super.m() calls use invokespecial, and static methods use invokestatic. With these instructions the body to run is known at compile time and the table is not consulted. Since Java 11, private instance methods are called with invokevirtual. But because they cannot be overridden, they have only one candidate and the JVM picks it directly.

Animal[] d = {new Dog(), new Cat()};
for (Animal h : d) {
    h.run();
    h.makeSound();
}
Table 4.4.7: Trace of the calls through the method table. The bytecode is the same at every call; only the table of the object changes.
CallBytecodeObjectSlot in the tableOutput
h.run()Animal.run, slot 1Dog #1Dog.runDog runs
h.makeSound()Animal.makeSound, slot 0Dog #1Dog.makeSoundWoof woof!
h.run()Animal.run, slot 1Cat #2Animal.run (by inheritance)Animal runs
h.makeSound()Animal.makeSound, slot 0Cat #2Cat.makeSoundMeow!
Stackhmain()Dog #1class →Dog table[0] makeSoundDog[1] runDog[2] sleepAnimal[3] barkDoginvokevirtual Animal.run → slot [1]Dog table [1] = Dog.run
Figure 4.4.13: The first h.run() call. The object is a Dog; slot 1 of its table holds Dog.run.
Stackhmain()Cat #2class →Cat table[0] makeSoundCat[1] runAnimal[2] sleepAnimal[3] scratchCatinvokevirtual Animal.run → slot [1]Cat table [1] = Animal.run (by inheritance)
Figure 4.4.14: The same bytecode, another object. Since Cat does not override run, slot 1 of its table points to Animal.run.

The four-line output of the program is the last column of the table. In none of the four calls was an if or a type test made; the tables made the choice. Comparing Figure 4.4.13 with Figure 4.4.14 shows that the difference lies only in the table the object is attached to. The path, the slot number and the bytecode are the same.

This structure also shows that the cost of dynamic binding is small. A virtual call costs only one or two more memory reads than a plain call. Modern JVMs often remove even that. If only objects of the same class are seen at a call site, the component that compiles while the program runs (the JIT compiler) can bind the call directly to that body. So there is no need to avoid polymorphism for performance reasons.

4.4.4.5What is not bound dynamically?

Dynamic binding applies only to instance methods that can be overridden. Fields, static methods, and private and final methods are bound statically: the compiler decides which to use by looking at the declared type of the reference.

class Animal {
    String kind = "mammal";

    static void info() {
        System.out.println("Animal.info()");
    }

    void introduce() {
        System.out.println("I am a " + kind);
    }
}

class Dog extends Animal {
    String kind = "dog"; // hides it

    static void info() {
        System.out.println("Dog.info()");
    }

    @Override
    void introduce() {
        System.out.println("I am a " + kind);
    }
}

These two classes show two different cases. Dog defines a new field called kind. This field does not override the kind field of Animal; it hides it: a Dog object has two separate kind fields. Dog also defines a static info() method with the same signature. static methods are not overridden either, they are hidden. introduce() is an ordinary instance method and is really overridden.

Definition 4.4.12

Defining in a subclass a field with the same name as a field in the superclass, or a static method with the same signature, is called hiding. The hidden member is not removed; it continues to exist in the object or the class. Which one is used is determined at compile time by the declared type of the reference.

Animal h = new Dog();
System.out.println(h.kind);
h.info();
h.introduce();
mammal
Animal.info()
I am a dog
Table 4.4.8: What is each kind of member chosen by?
MemberChosen byBinding
Instance methodObject typeDynamic
Field (variable)Reference typeStatic
static methodReference typeStatic
private / final methodCannot be overridden; there is one candidateStatic

A final method cannot be overridden in a subclass; if it is attempted, the compiler says overridden method is final. A private method is invisible to the subclass. If the subclass writes a method with the same name, it is a new, unrelated method. In both cases there is only one candidate for the call and the choice is known at compile time.

A static method belongs to the class, not to an object. Java allows a call through a reference such as h.info(), but this notation is misleading. The compiler quietly turns the call into Animal.info(); the object the reference points to is never looked at. Even if the reference is null, the call works and no NullPointerException occurs. That is why a static method is always called with the class name: Dog.info(). Defining a field with the same name as one in the superclass is also avoided.

4.4.4.6Code trace: field hiding and static

The same idea can be traced step by step in a short program written with methods that return values.

class Animal {
    String kind = "mammal";
    static String info() { return "Animal.info"; }
    String introduce() { return "I am a " + kind; }
}
class Dog extends Animal {
    String kind = "dog";            // hides
    static String info() { return "Dog.info"; }
    String introduce() { return "I am a " + kind; }
}
Animal h = new Dog();   // main
System.out.println(h.kind);
System.out.println(h.info());
System.out.println(h.introduce());
System.out.println(((Dog) h).kind);
mammal
Animal.info
I am a dog
dog
StackHeapmain()hDog #1Animal.kind"mammal"Dog.kind"dog"one object, two separate kind fields
Figure 4.4.15: One object, two separate kind fields. The kind in Dog does not override the one in Animal; both are in the object.
Table 4.4.9: Trace of the field hiding program. The declared type of h is Animal and the object it points to is a Dog.
ExpressionKind of memberSelection criterionSelectedOutput
h.kindFieldDeclared type AnimalAnimal.kindanimal
h.info()static methodDeclared type AnimalAnimal.info()Animal.info
h.introduce()Instance methodActual type DogDog.introduce(); inside it kind = Dog.kindI am a dog
((Dog) h).kindFieldDeclared type Dog (by the cast)Dog.kinddog

The third line needs extra attention. h.introduce() is bound dynamically and Dog.introduce() runs. The expression kind inside this method is also a field access, and it too is bound statically. But this time the declared type is the class in which the method is written. In code written in class Dog, kind means this.kind, and the type of this is Dog. So Dog.kind is read and I am a dog is printed.

StackHeapDog.introduce()thismain()hDog #1Animal.kind"mammal"Dog.kind"dog"instance method → actual type (Dog)
Figure 4.4.16: The call h.introduce(). The instance method is chosen by the actual type; the this inside Dog.introduce() has type Dog and reads Dog.kind.

For comparison, suppose introduce() were not overridden in Dog. Then h.introduce() would run the body in Animal. Since this body is written in class Animal, the kind inside it is Animal.kind and the output would be I am a mammal. The object is still a dog. This is the confusing side of field hiding: the same object holds two values under the same name, and which one is read depends on where the code is written.

On the last line the cast makes the declared type of the expression Dog. The other field of the same object is read: dog. The object has not changed; only the type the compiler looks at has.

Common mistake

Thinking fields are overridden too. h.kind is always read by the reference type. If information that varies by subclass is needed, the field is made private and a method (getter) that returns the information is written. A method can be overridden; a field cannot.

4.4.4.7Calling an overridable method from a constructor

Dynamic binding works while an object is being built, too. This creates an unexpected trap: the constructor of a superclass can run a method that uses fields of the subclass that have not been prepared yet.

class Component {
    Component() {
        System.out.println("Building Component");
        draw();
    }
    void draw() { System.out.println("empty"); }
}
class Label extends Component {
    private String text = "Hello";
    Label() { System.out.println("Label built"); }
    @Override void draw() {
        System.out.println("Label: " + text);
    }
}
Label e = new Label();   // main
e.draw();
Building Component
Label: null
Label built
Label: Hello

The second line of the output is surprising. The field text was given the value "Hello" in its declaration, yet Label: null is printed. The reason is the order in which things are done while the object is built.

Table 4.4.10: Trace of the call new Label().
StepCode runningtextOutput
1new reserves space for the object; the fields get their default valuesnull—
2The first job of Label() is the implicit super() callnull—
3Body of Component(), first linenullBuilding Component
4draw() = this.draw(); the object is a Label → Label.draw()nullLabel: null
5super() returned; the subclass's field initializers run"Hello"—
6Body of Label()"Hello"Label built
7main: e.draw()"Hello"Label: Hello

The critical point is the order of steps 4 and 5. In Java a subclass constructor first runs the superclass constructor. The initial values given to the subclass's fields in their declarations are assigned after the superclass constructor returns. The draw() call in Component() is bound dynamically; since the class of the object is Label, the overridden version is chosen. At that moment text is still at its default value null. The subclass's method runs on a half-built object.

StackHeapLabel.draw()Component()Label()main()e?Label #1textnullLabel.draw() chosen, text = null
Figure 4.4.17: Step 4. On the stack are Label(), above it Component() and at the top Label.draw(). The text field of the object on the heap is still null.
StackHeapLabel()main()e?Label #1text"Hello"super() returned → field initializers
Figure 4.4.18: Step 5. After super() returns, the field initializer runs and "Hello" is assigned to text. draw() has long since been called.

In this example the harm is small because the method only prints the field. Had the method used the field, for example by calling text.length(), the program would have crashed:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "this.text" is null
	at Label.draw(Main.java:21)
	at Component.<init>(Main.java:16)
	at Label.<init>(Main.java:19)

Since JDK 15 the NullPointerException message also says by default which expression was null: "this.text" is null. The order of the lines in the stack trace sums up the situation too. At the top is Label.draw, where the error occurred, below it the Component constructor that called it, and below that the Label constructor. <init> is the name of a constructor in bytecode. The chain starts at the constructor of Label and draws a loop that returns to a method of Label.

Definition 4.4.13

The constructor rule: Only private, final or static methods should be called from a constructor. These methods cannot be overridden; so they cannot reach the not-yet-built state of the subclass.

Common mistake

Calling an overridable method in a superclass constructor with a “template” intention (like draw(), init(), load()). If a subclass overrides this method, the method runs before the subclass's fields are assigned. The result is wrong output with null, 0 or false values, or a NullPointerException. If such preparation work is needed, it is called separately after the object is built.

4.4.5Overloading

Method overloading is defining several methods with the same name but different parameter lists. It is a familiar tool from the topic of methods: Math.abs has int, long, float and double versions; println has ten versions. When used together with inheritance and dynamic binding, one property of overloading becomes important: the choice is made at compile time.

4.4.5.1Overloading is resolved at compile time

static void print(Animal h) {
    System.out.println("print(Animal)");
}

static void print(Dog k) {
    System.out.println("print(Dog)");
}

public static void main(String[] args) {
    Dog dog = new Dog();
    Animal animal = dog;
    print(dog);
    print(animal);
    print((Dog) animal);
}
print(Dog)
print(Animal)
print(Dog)

All three calls of the program are made with the same object. Even so, the second call chooses a different version. In the first call the argument is dog and its declared type is Dog; both versions fit, but print(Dog) is more specific. In the second call the argument is animal. Even though the object is a dog, the declared type of animal is Animal and the compiler knows only that. An argument of type Animal does not fit print(Dog); the only candidate is print(Animal). In the third call the explicit cast makes the declared type of the expression Dog, and print(Dog) is chosen again.

Definition 4.4.14

The compiler chooses among overloaded versions by the declared types of the arguments. The chosen signature is written into the bytecode and does not change while the program runs. The actual class of the objects the arguments point to does not affect this choice.

This rule is the exact opposite of the rule for overriding. In overriding, the actual type of the object decides; in overloading, the declared type of the argument. Table 4.4.11 puts the two mechanisms side by side.

Table 4.4.11: Comparison of overloading and overriding.
OverloadingOverriding
Where?Same class (or a class and its subclass)Subclass
SignatureDifferent parameter listSame signature
Who choosesThe compilerThe JVM
CriterionDeclared type of the argumentActual type of the receiver object
WhenCompile timeRun time

The phrase “receiver object” in the table needs a separate explanation. In the call a.m(b), a is the receiver: it says on which object the method is called. b is the argument. In Java, dynamic binding looks only at the type of the receiver. There is no run-time choice that looks at the types of the arguments; for the arguments everything is settled at compile time. That is why Java's dynamic binding is called single dispatch.

One more detail concerns the return type. The signature of a method consists only of the name and the parameter types; the return type is not part of the signature. So two methods that differ only in return type cannot be overloaded. If static int g(int x) and static long g(int x) are written in the same class, the compiler says method g(int) is already defined.

4.4.5.2The most specific version and ambiguity

An argument can fit several versions. In that case the compiler chooses the most specific one.

Definition 4.4.15

If every parameter type of one of two candidate methods is a subtype of (or the same as) the corresponding parameter type of the other, that method is more specific. The compiler chooses the most specific among the matching candidates. If there is no single most specific candidate, the call is ambiguous and gives a compile error.

static void show(Object o) { System.out.println("show(Object)"); }
static void show(Animal h) { System.out.println("show(Animal)"); }
static void show(String s) { System.out.println("show(String)"); }
// in main:
show(new Cat());
show("a");
Object o = "a";
show(o);
show((Animal) null);
show(Animal)
show(String)
show(Object)
show(Animal)

Let us examine the four calls in order. show(new Cat()): a cat fits both Animal and Object, not String. Animal is a subtype of Object, so it is more specific: show(Animal). show("a"): the argument fits the String and Object versions; String is more specific. show(o): even though the object o points to is a string, its declared type is Object. An argument of type Object fits only show(Object).

The fourth call uses a special value. null fits every reference type; so when show(null) is written, all three versions are candidates. Object is the most general and is eliminated. But there is no inheritance relationship between Animal and String; neither is more specific than the other. The compiler cannot choose:

error: reference to show is ambiguous
  both method show(Animal) in Main and
  method show(String) in Main match

The solution is to fix the declared type of the expression with an explicit cast: show((Animal) null). The value of the expression (Animal) null is still null, but its type is Animal. Now the String version does not fit and show(Animal) is chosen. This is the fourth line in the output.

If the matching versions lie on a single inheritance chain, there is no ambiguity. With show(Object), show(Animal) and show(Cat), show(null) compiles and chooses the lowest one, show(Cat), because Cat is a subtype of both other types. Ambiguity arises only when two candidates that are not subtypes of each other fit at the same time.

Common mistake

Passing null when there are two unrelated overloads: show(null) → reference to show is ambiguous. Which version is wanted is stated with an explicit cast: show((String) null) or show((Animal) null).

4.4.5.3Code trace: the compiler or the JVM?

The most instructive case is the one where the two mechanisms work together in the same call. In the program below print is overloaded; in each version the overridden makeSound() is also called.

static void print(Animal h) {
    System.out.print("print(Animal): ");
    h.makeSound();
}
static void print(Dog k) {
    System.out.print("print(Dog): ");
    k.makeSound();
}
// in main:
Animal animal = new Dog();
Animal other = new Cat();
print(animal);
print(other);
print((Dog) animal);
print(Animal): Woof woof!
print(Animal): Meow!
print(Dog): Woof woof!
Table 4.4.12: Two decisions in every call. The compiler chooses the version of print, the JVM the version of makeSound().
CallDeclared type of the argumentCompiler's choiceObjectJVM's choiceOutput
print(animal)Animalprint(Animal)DogDog.makeSound()print(Animal): Woof woof!
print(other)Animalprint(Animal)CatCat.makeSound()print(Animal): Meow!
print((Dog) animal)Dogprint(Dog)DogDog.makeSound()print(Dog): Woof woof!
Compilerlooks at the declared typeJVMlooks at the class of the objectargument type: Animalprint(Animal)print(Dog)object: DogDog.makeSound()Cat.makeSound()compile timerun time
Figure 4.4.19: Two decisions in the first call. The compiler looked at the declared type (Animal) and chose print(Animal); inside the method the JVM looks at the object (Dog) and chooses Dog.makeSound().

In the first two calls the declared types of the variables are the same, and the objects they point to differ. The compiler chooses the same version, print(Animal), in both calls. The h.makeSound() inside the method is an overridden method, and the JVM looks at the object each time: first Woof woof!, then Meow!. In the third call the explicit cast changes the declared type of the expression and the compiler chooses print(Dog).

The trace can be summed up in one sentence: the overloading choice is made at compile time with the declared type, the overriding choice at run time with the actual type. To find out what a call prints, two questions are asked in order. First, “which signature does the compiler choose?”, then “which class's body of that signature runs?”.

4.4.5.4The three phases of overload resolution

When the argument is a primitive value, the choice gets one step more complicated. An int can be widened to long; it can be boxed to Integer; it can also be passed to an int... parameter. The compiler tries these routes not at the same time but in order.

Definition 4.4.16

The compiler searches overloaded versions in three phases:

  1. The phase without boxing. Only an exact match, primitive widening (int → long) and reference widening (String → Object) are tried.
  2. The boxing phase. If there is no candidate in phase 1, automatic boxing and unboxing are tried too: double → Double → Object.
  3. The variable-arity phase. If there is still no candidate, versions with variable arity such as int... come into play.

If at least one candidate is found in a phase, later phases are not reached. The most specific among that phase's candidates is chosen.

The most surprising consequence of the rule is this: with f(long) and f(Integer), the call f(5) chooses f(long). Integer is the wrapper class of int and looks closer at first sight. But reaching it needs boxing; long is reached by widening, in phase 1. Widening comes before boxing for historical reasons. Boxing was added in Java 5. Until then f(5) called f(long). Boxing was put in the second phase so that the new rule would not change the behavior of old programs.

Narrowing (long → int, double → long) is tried in no phase. If no candidate is found in any of the three phases, the compiler says no suitable method found. For example, with only print(Animal) and print(Dog), writing print(true) gives the message no suitable method found for print(boolean).

This order is applied at compile time and the chosen signature is written into the bytecode. Which class's body of the chosen signature runs is again determined at run time. The three phases answer only the question “which signature?”.

static void f(long x)    { p("f(long)"); }
static void f(Integer x) { p("f(Integer)"); }
static void f(Object x)  { p("f(Object)"); }
static void f(int... x)  { p("f(int...)"); }
// in main (p: System.out.println):
byte b = 1;
f(5);
f(b);
f(Integer.valueOf(5));
f("x");
f(2.5);
f();
f(1, 2);
f(long)
f(long)
f(Integer)
f(Object)
f(Object)
f(int...)
f(int...)
Table 4.4.13: Resolving seven calls phase by phase.
CallArgument typePhase 1 candidatesPhase 2Phase 3Chosen
f(5)intf(long) (widening)——f(long)
f(b)bytef(long) (widening)——f(long)
f(Integer.valueOf(5))Integerf(Integer), f(Object)——f(Integer) (more specific)
f("x")Stringf(Object)——f(Object)
f(2.5)doublenonef(Object) (boxing to Double)—f(Object)
f()—nonenonef(int...)f(int...)
f(1, 2)int, intnonenonef(int...)f(int...)
Argument: 5 (int)1. without boxing2. boxing3. variable arityf(long)✓ int → long wideningf(Integer)✗ needs boxingf(Object)✗ needs boxingf(int...)the only candidate in phase 1: f(long)
Figure 4.4.20: The phases for f(5). In phase 1 only long fits, by widening; Integer and Object need boxing and are not tried in this phase.

A few rows of the table need a separate explanation. In f(b) the argument is a byte, and it also widens to long. Even if it were boxed, it would become a Byte, not an Integer; there is no relationship between Byte and Integer. In f(Integer.valueOf(5)) the argument is already an object. In phase 1 there are two candidates: f(Integer) by exact match and f(Object) by reference widening. Integer is chosen because it is more specific than Object. f(long) needs unboxing and is not tried in this phase.

Argument: 2.5 (double)1. without boxing2. boxing3. variable arityf(long)✗ double → long narrowingf(Integer)✗ Double ≠ Integerf(Object)✓ double → Double → Objectf(int...)phase 1 empty → boxing in phase 2
Figure 4.4.21: The phases for f(2.5). A double cannot be narrowed to long; phase 1 stays empty. In phase 2 it is boxed to Double and fits Object.

The line f(2.5) shows that narrowing is never tried. Going from double to long loses information; the compiler does not do it by itself. When phase 1 stays empty, phase 2 is entered. 2.5 is boxed to Double. Double does not fit Integer, but it fits Object. In the last two calls there are zero or two arguments. Only the int... parameter accepts these counts, and it is consulted last, in phase 3.

Example 4.4.4

For the same four versions (f(long), f(Integer), f(Object), f(int...)), which versions do short s = 3; f(s);, f('A'); and f(Long.valueOf(4)); choose?

f(s): short widens to long; in phase 1 the only candidate is f(long).

f('A'): char is also an integral type and widens to long: f(long). The code of the character, 65, is passed as a long.

f(Long.valueOf(4)): the argument is a Long object. f(long) needs unboxing and is not tried in phase 1. Long does not fit Integer. In phase 1 the only candidate, by reference widening, is f(Object).

Common mistake

Thinking boxing comes first. With f(long) and f(Integer), f(5) calls f(long), not f(Integer): widening is in phase 1, boxing in phase 2.

4.4.6Inheritance and polymorphism

The real value of polymorphism shows in the design of a program. Polymorphic code is shorter than code that tests types and more robust against new classes. Most of the examples are built on a shape hierarchy.

4.4.6.1The relationship between inheritance and polymorphism

The relationship between the two concepts is one-directional. Run-time polymorphism requires inheritance: without a class hierarchy there is neither overriding nor dynamic binding. Using inheritance, on the other hand, does not require polymorphism. A class can be derived from another just to reuse code. Inheritance builds the hierarchy; polymorphism makes use of that hierarchy.

If class B is a subclass of A, an object of B can behave like an object of A; the reverse is not true. Assigning an A reference to a B reference needs a narrowing cast, and the cast is written in parentheses.

A objA = new B(); // B acts as an A
B objB = (B) objA; // legal, but
                   // use with care
A objAB object(B) objA → ✓ succeedsA objAA object(B) objA → ✗ ClassCastException
Figure 4.4.22: The two possible results of the cast (B) objA. If objA points to a B object, the cast succeeds; if it points to a plain A object, ClassCastException is thrown.

The last line compiles. At run time, if objA does not really point to a B object, ClassCastException is thrown. The “use with care” comment in the code describes this risk.

In Java, class inheritance is not the only source of polymorphism. Interfaces provide the same mechanism. The object of any class that implements an interface (implements) can be assigned to a reference of that interface type. A class can derive from only one superclass, but it can implement many interfaces. The same dynamic binding works with an interface type such as SoundMaker s instead of Animal h.

4.4.6.2A shape hierarchy

Suppose a drawing program has squares, rectangles and circles. Every shape has a name; every shape's area and perimeter can be computed; every shape can be drawn. But area and perimeter are found with a different formula in each shape. This common structure is gathered in an abstract superclass.

abstract class Shape {
    private String name;

    public Shape(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public abstract double area();

    public abstract double perimeter();

    public void draw() {
        System.out.println(name + " drawn.");
    }
}
Shape-name: String+getName(): String+area(): double+perimeter(): double+draw(): voidSquare-side: double+area()+perimeter()+draw()Rectangle-width: double-height: double+area()+perimeter()Circle-radius: double+area()+perimeter()+draw()
Figure 4.4.23: The abstract class Shape and its subclasses Square, Rectangle, Circle. Names and methods in italics are abstract. Rectangle does not override draw().

The word abstract at the head of class Shape declares that the class is abstract. An object cannot be created directly from an abstract class; if new Shape("x") is written, the compiler says Shape is abstract; cannot be instantiated. area() and perimeter() are abstract methods too: they have no body and every concrete subclass must write them. draw() is an ordinary method with a body. Subclasses can use it as it is or override it. The name field is private; subclasses reach it through the constructor and getName().

An abstract class is an ideal superclass for polymorphism. The question “what is the area of a shape?” has no general answer; only a concrete shape can give it. An abstract method expresses this situation: “every shape has an area, but the subclass says how it is computed.”

class Square extends Shape {
    private double side;
    public Square(double side) {
        super("Square");
        this.side = side;
    }
    @Override
    public double area() {
        return side * side;
    }
    @Override
    public double perimeter() {
        return 4 * side;
    }
    @Override
    public void draw() {
        System.out.println("Square drawn: side " + side);
    }
}

The constructor of Square passes the name to the superclass with super("Square") and keeps the side length in its own field. It overrides all three methods. If Square did not write the abstract methods, it would not compile unless it were declared abstract.

class Rectangle extends Shape {
    private double width;
    private double height;
    public Rectangle(double width, double height) {
        super("Rectangle");
        this.width = width;
        this.height = height;
    }
    @Override
    public double area() {
        return width * height;
    }
    @Override
    public double perimeter() {
        return 2 * (width + height);
    }
    // no draw() → Shape's is used
}

Rectangle overrides area and perimeter but does not override draw(). When a rectangle is drawn, Shape.draw() runs and prints Rectangle drawn. using the name. The comment at the end of the code reminds of this.

class Circle extends Shape {
    private double radius;
    public Circle(double radius) {
        super("Circle");
        this.radius = radius;
    }
    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
    @Override
    public double perimeter() {
        return 2 * Math.PI * radius;
    }
    @Override
    public void draw() {
        System.out.println("Circle drawn: radius " + radius);
    }
}

Circle computes the area and perimeter with the constant Math.PI and overrides draw() with its own information, printing the radius too.

4.4.6.3Code trace: an array of shapes

Shape[] shapes = new Shape[3];
shapes[0] = new Square(5);
shapes[1] = new Rectangle(4, 6);
shapes[2] = new Circle(7);

for (Shape shape : shapes) {
    System.out.println(shape.getName()
        + " area: " + shape.area());
    shape.draw();
}
Square area: 25.0
Square drawn: side 5.0
Rectangle area: 24.0
Rectangle drawn.
Circle area: 153.93804002589985
Circle drawn: radius 7.0

The array has type Shape; its elements point to objects of three different subclasses. In every round the loop makes the same two calls: shape.area() and shape.draw(). getName() is not overridden in any subclass; in every round the version of Shape runs and returns the name given in the constructor.

Table 4.4.14: Trace of the shape array loop.
RoundObjectarea()Areadraw()
1Square(5)Square: 5 × 525.0Square.draw()
2Rectangle(4, 6)Rectangle: 4 × 624.0Shape.draw() (not overridden)
3Circle(7)Circle: π × 7 × 7153.93804002589985Circle.draw()
shapesheap0Square (5)1Rectangle (4, 6)2Circle (7)
Figure 4.4.24: The second round. shapes[1] points to a Rectangle. Since Rectangle does not override draw(), the search climbs up and Shape.draw() runs.

The area of the circle is 49π. double arithmetic computes this value as 153.93804002589985, and println prints all significant digits. If a more readable output is wanted, printf("%.2f", ...) is used.

4.4.6.4Why polymorphism?

The value of polymorphism is seen by comparison with code written without it. The method below finds the area of a shape by testing types.

static double badArea(Shape s) {
    double area;
    if (s instanceof Square) {
        area = ((Square) s).area();
    } else if (s instanceof Rectangle) {
        area = ((Rectangle) s).area();
    } else if (s instanceof Circle) {
        area = ((Circle) s).area();
    } else {
        area = 0; // new type forgotten!
    }
    return area;
}

The method works correctly, but it is fragile. When a new shape is added to the hierarchy, this method must change too. If a class RightTriangle extends Shape is written and the method is not updated, badArea(new RightTriangle(3, 4)) returns 0.0 without any error. Every instanceof chain in a program is a place that can be forgotten when a new class is added. Moreover, the casts in the method are unnecessary: area() is already defined in Shape and can be called without a cast.

static double totalArea(Shape[] arr) {
    double total = 0;
    for (Shape shape : arr) {
        // each object knows its area
        total += shape.area();
    }
    return total;
}

In the polymorphic version there is no type test at all. Each object computes its own area. It is enough to add a new class RightTriangle extends Shape; totalArea does not change at all. For example, for the array {Square(5), Rectangle(4, 6), RightTriangle(3, 4)} the result is 25 + 24 + 6 = 55.0. The code gets shorter and the risk of ClassCastException disappears.

Definition 4.4.17

The open/closed principle: A software unit should be open for extension and closed for modification. New behavior is added not by changing existing code but by adding new code (for example a new subclass).

totalArea follows this principle: it extends with new shapes but does not change itself. badArea breaks the principle. In large programs the difference is much more marked. A shape editor may have dozens of operations such as area, perimeter, drawing, saving and printing. In a design that tests types, a new shape requires touching all of these operations; in a polymorphic design only the new class is written.

Example 4.4.5

Let RightTriangle(a, b) be added to the shape hierarchy: area = a·b/2, perimeter = a + b + hypotenuse. Let draw() not be overridden and the constructor call super("Right triangle"). For RightTriangle(3, 4), what are the area, the perimeter and the output of draw()?

Area: 3 · 4 / 2 = 6.0. Hypotenuse: √(3² + 4²) = √25 = 5, perimeter: 3 + 4 + 5 = 12.0. Since draw() is not overridden, Shape.draw() runs: Right triangle drawn.

Nothing changes in the shape loop; only a new object is added to the array. For the perimeter, a + b + Math.sqrt(a * a + b * b) is written in the code.

4.4.6.5Polymorphic parameters and return values

Polymorphism is used not only in arrays but also in method parameters and return values.

class Vet {
    void examine(Animal h) {     // any subclass
        System.out.print("Exam: ");
        h.makeSound();
    }
    static Animal adopt(String kind) { // hidden
        if (kind.equals("cat")) return new Cat();
        return new Dog();
    }
}
// in main:
Vet v = new Vet();
v.examine(new Cat());
Animal h = Vet.adopt("dog");
v.examine(h);
System.out.println(h.getClass().getSimpleName());
Exam: Meow!
Exam: Woof woof!
Dog

The parameter of the examine method has type Animal. So the method accepts objects of every subclass that exists today and that will be written in the future. In the first call a cat is examined, in the second a dog; the h.makeSound() inside the method runs the object's own version every time. When a new class Bird is added to the hierarchy, examine does not change.

The return type of the adopt method is Animal too. The method hides from the caller which subclass it produces. The caller relies only on the Animal contract: the object returned can make a sound, run and sleep. If adopt starts returning another subclass later, the code that uses it is not affected. The getSimpleName() on the last line gives the name of the actual class of the object without the package name: Dog.

Definition 4.4.18

A factory method is a method that produces an object and returns it as a superclass or interface type. The caller does not have to know which concrete class was produced.

A general principle comes out of this example: parameter and variable types are chosen as the most general type that is enough to do the job. Since examine only calls makeSound(), a parameter of type Animal is enough; a parameter of type Dog would leave the cat out needlessly. The same principle is seen in the Java library: variables are mostly declared with type List<String> rather than ArrayList<String>.

4.4.6.6The anti-tank game

The use of polymorphism in a game is a more realistic example. In an anti-tank game written with Swing, tanks fall from the top of the screen; the player fires shells at them with the anti-tank gun at the bottom. When the score is a multiple of 10, the type of the gun changes and it starts firing a different shell.

AntiTankx, y: intcolor: Color+fire(): ShellAT Javelin+fire(): ShellAT Tow2A+fire(): ShellShellshellPos: Rectanglecolor: ColorShell37mmShell57mm
Figure 4.4.25: The two hierarchies of the anti-tank game. Two subclasses override the fire() method of the abstract class AntiTank; class Shell also has subclasses Shell37mm and Shell57mm.

In the figure, “AT Javelin” is the class AntiTankJavelin and “AT Tow2A” is the class AntiTankTow2A. Class Tank also has subclasses TankT90MS and TankLeopard2A4. The game loop knows only the types AntiTank and Tank.

AntiTank weapon = new AntiTankJavelin(x, y);
...
// which shell? depends on the object (dynamic binding)
shells.add(weapon.fire());
...
if (weapon instanceof AntiTankJavelin) {
    weapon = new AntiTankTow2A(weapon.x, weapon.y);
}

The line shells.add(weapon.fire()) does not know which shell will be produced. fire() is an abstract method; the call is bound dynamically and the version of whatever class the gun is at that moment runs. The return type is Shell; the object returned may be Shell37mm or Shell57mm. The shells list also holds objects of type Shell and moves and draws all of them with the same loop.

The instanceof test in the code does a different job: upgrading the gun. The test is made only once, at upgrade time; not at every shot. The new gun object takes the position (x, y) of the old one and the variable weapon now points to it. The declared type of the variable has not changed; only the object it points to has. From this moment on the same fire() call runs another body.

Shell t1 = weapon.fire(); // Javelin
// → Shell37mm, height 30
weapon = new AntiTankTow2A(100, 540);
Shell t2 = weapon.fire();
// → Shell57mm, height 40

A test output independent of the game confirms this. The same fire() call produces a different shell when the gun changes: Javelin fires a Shell37mm with height 30, Tow2A a Shell57mm with height 40. No if on the type of the shell is needed in the game code. To add a new kind of gun, only a new subclass and a new shell class are written.

4.4.6.7equals and inheritance: the symmetry trap

The methods of Object are bound dynamically too. When Object o = k1; System.out.println(o); is written, println calls o.toString() and the object's own toString runs. o.equals(x) likewise runs the object's own equals. This makes collections work correctly with every class. Methods such as ArrayList.contains and HashSet.add know only the type Object, but they call the elements' own equals and hashCode methods.

The equals method must obey certain rules. One of them is symmetry: if x.equals(y) is true, y.equals(x) must be true too. Once inheritance is involved, this rule is easily broken.

class Point {
    final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
    @Override public boolean equals(Object o) {
        if (!(o instanceof Point)) return false;
        Point n = (Point) o;
        return x == n.x && y == n.y;
    }
    @Override public int hashCode() { return 31 * x + y; }
}
class ColoredPoint extends Point {
    final String color;
    ColoredPoint(int x, int y, String color) {
        super(x, y);
        this.color = color;
    }
    @Override public boolean equals(Object o) {
        if (!(o instanceof ColoredPoint)) return false;
        ColoredPoint r = (ColoredPoint) o;
        return super.equals(r) && color.equals(r.color);
    }
}

Point counts two points equal if their coordinates are equal. ColoredPoint adds the color condition to this and requires the other side to be a ColoredPoint as well. Each of the two classes is reasonable when looked at separately. A problem arises when they are used together:

Point p = new Point(1, 2);
ColoredPoint k =
    new ColoredPoint(1, 2, "red");
System.out.println(p.equals(k)
    + " " + k.equals(p));
true false

The receiver object determines which equals runs. In the call p.equals(k) the receiver is p and the method of Point runs. k is a ColoredPoint, therefore a Point; the coordinates are equal and the result is true. In the call k.equals(p) the receiver is k and the method of ColoredPoint runs. p is not a ColoredPoint; the result is false. Symmetry is broken.

This breakage causes inconsistent behavior in collections. In a list that contains k, contains(p) gives true, because the list calls p.equals(k). In a list that contains p, contains(k) gives false. If p and then k are added to a HashSet, the set has 2 elements. If k and then p are added, it has 1 element. The contents of the set have come to depend on the order in which the elements were added.

Table 4.4.15: Consequences of broken symmetry in collections. p = Point(1, 2), k = ColoredPoint(1, 2, "red").
OperationCalled insideResult
[k].contains(p)p.equals(k)true
[p].contains(k)k.equals(p)false
HashSet: first p, then kk.equals(p)2 elements
HashSet: first k, then pp.equals(k)1 element

There are two known solutions to the problem. The first is to use a getClass() comparison instead of instanceof in both classes. That way only objects of exactly the same class count as equal, and p.equals(k) is false too:

// in Point:
@Override public boolean equals(Object o) {
    if (o == null || getClass() != o.getClass()) return false;
    Point n = (Point) o;
    return x == n.x && y == n.y;
}
// in ColoredPoint:
@Override public boolean equals(Object o) {
    if (!super.equals(o)) return false;   // class and coordinates
    return color.equals(((ColoredPoint) o).color);
}

With this solution p.equals(k) and k.equals(p) both give false; two points of the same color come out equal. The price is this: even an ordinary subclass of Point that adds no field is no longer counted equal to a Point.

The second solution is composition instead of inheritance. ColoredPoint does not derive from Point; it holds a Point field and carries a color as well. Since there is no is-a relationship between the two classes, comparing them with each other also loses its meaning. If the position of a colored point is needed, it is obtained as a Point with a method such as position().

class ColoredPoint {              // no extends
    private final Point position;
    private final String color;
    ColoredPoint(int x, int y, String color) {
        this.position = new Point(x, y);
        this.color = color;
    }
    Point position() { return position; }
    @Override public boolean equals(Object o) {
        if (!(o instanceof ColoredPoint)) return false;
        ColoredPoint r = (ColoredPoint) o;
        return position.equals(r.position) && color.equals(r.color);
    }
    @Override public int hashCode() { return 31 * position.hashCode() + color.hashCode(); }
}
Common mistake

Extending equals in a subclass in one direction only. If the subclass adds a new condition to equals while the superclass keeps the old rule, p.equals(k) is true and k.equals(p) is false. Symmetry breaks and collections become inconsistent.

4.4.7Worked problems

The problems below require using the rules explained in the notes together. In each problem the code is given first, then the solution is explained step by step. All outputs were verified by running them with JDK 21.

Example 4.4.6

Problem 1: What is the output? call() is defined only in A and calls print() from inside. B overrides only print().

class A {
    void print() {
        System.out.println("A.print");
    }

    void call() {
        print(); // this.print()
    }
}

class B extends A {
    @Override
    void print() {
        System.out.println("B.print");
    }
}

// in main:
A a = new B();
a.call();
new A().call();

a.call(): the object a points to is a B. B has no call(); the search climbs up and A.call() runs. The print() inside this method is really this.print(). this is the object the method was called on, that is a B object. this.print() is bound dynamically too and B.print() runs: B.print.

new A().call(): the object is an A; this.print() inside A.call() runs A.print(): A.print.

B.print
A.print

The lesson of the problem is this: the code of a superclass may unknowingly call a method that a subclass overrides. The programmer who wrote A may have thought that call() would call A.print(). But every call made through this is bound dynamically.

Example 4.4.7

Problem 2: Does it compile, does it run? For each line, the verdict is to be given: compile error, run-time error, or no problem (with its output).

Animal h = new Cat();
Cat k1 = h;              // (1)
Cat k2 = (Cat) h;       // (2)
Dog k3 = (Dog) h;     // (3)
h.scratch();              // (4)
((Cat) h).scratch();     // (5)
Object o = new Dog();
o.makeSound();             // (6)
((Animal) o).makeSound();  // (7)
#ResultReason
1Compile errorAnimal → Cat needs an explicit cast: incompatible types: Animal cannot be converted to Cat.
2No problemThe object really is a Cat.
3Run-time errorIt compiles, but the object is a cat: ClassCastException.
4Compile errorAnimal has no scratch(): cannot find symbol.
5No problemPrints Cat scratches.
6Compile errorObject has no makeSound().
7No problemDynamic binding: prints Woof woof!.

The method of solution is the same for every line. First the compiler's question is asked: is the assignment or call valid by the declared types? If it is, the JVM's question is asked: looking at the object, does the cast succeed, and which version runs? In lines 1 and 4 the compiler knows that h is an Animal; it does not know it is a cat. In line 7 the cast is downward (Object → Animal) and the object is a dog; Dog.makeSound() runs.

Example 4.4.8

Problem 3: Overloading and overriding. Parent has two overloaded f methods; Child overrides only f(Object). What do the two calls print?

class Parent {
    void f(Object o) {
        System.out.println("Parent.f(Object)");
    }

    void f(String s) {
        System.out.println("Parent.f(String)");
    }
}

class Child extends Parent {
    @Override
    void f(Object o) {
        System.out.println("Child.f(Object)");
    }
}

// in main:
Parent u = new Child();
Object o = "hello";
u.f(o);
u.f("hello");

u.f(o): first the compiler chooses the version. The declared type of u is Parent; the candidates are f(Object) and f(String). The declared type of o is Object; only f(Object) fits. That the object it points to is a string does not change this choice. At run time the receiver object is a Child and has overridden f(Object): Child.f(Object).

u.f("hello"): the argument is a String; both versions fit, and f(String) is more specific. Since Child does not override this version, Parent.f(String) runs.

Child.f(Object)
Parent.f(String)

The order is always the same: first overloading (compile time, declared type), then overriding (run time, object type).

Example 4.4.9

Problem 4: Construction, phase, array. For the classes below, what do new Child(); and then new Child().show(); print?

class Parent {
    Parent() { show(); }
    void show() { System.out.println("Parent"); }
}
class Child extends Parent {
    private int[] arr = {1, 2, 3};
    @Override void show() {
        System.out.println(arr == null
            ? "no arr" : "length " + arr.length);
    }
}

During every new Child(), Parent() runs first and calls show(). The call is bound dynamically; Child.show() runs. At that moment the field arr has not yet been given its initial value and is null: no arr. On the second line a new object is created and the same thing happens again: no arr again. Then show() is called on the built object; now arr is ready: length 3. The output is three lines: no arr, no arr, length 3.

The second question of the same problem: do Object[] d = new String[1]; d[0] = 1; compile, do they run? They compile: a String[] can be assigned to an Object[] reference, and 1 can be boxed to Integer and written as an Object. At run time, however, the array is really a String[]: ArrayStoreException: java.lang.Integer.

Example 4.4.10

Problem 5: Salaries. The salary() method of class Employee returns the base salary. Manager overrides it with base × 1.5, Intern with a fixed 5000. For Employee[] = {Ayşe 20000, Manager Mehmet 30000, Intern Can} what is the total salary?

class Manager extends Employee {
    Manager(String name, double baseSalary) { super(name, baseSalary); }
    @Override double salary() { return baseSalary * 1.5; }
}
class Intern extends Employee {
    Intern(String name) { super(name, 0); }
    @Override double salary() { return 5000; }
}
// in main:
Employee[] cs = { new Employee("Ayşe", 20000), new Manager("Mehmet", 30000),
                 new Intern("Can") };
double total = 0;
for (Employee c : cs) total += c.salary();
System.out.println(total);   // 70000.0

The loop knows only the type Employee; in every round c.salary() runs the object's own version. Ayşe is a plain employee: 20000. Mehmet is a manager: 30000 × 1.5 = 45000. Can is an intern: 5000. The total is 20000 + 45000 + 5000 = 70000.0. Since the result is a double, it is printed with a decimal point.

Example 4.4.11

Problem 6: X, Y, Z. In X, name() returns "X" and print() does println(name()). Y extends X overrides only name() to return "Y". Z extends Y overrides only print() as println("Z:" + name()). If print() is called for every element of the array {new X(), new Y(), new Z()}, what is the output?

X: X.print() → X.name(): X. Y: Y has no print(), so X.print() runs; but the name() inside it, because this is a Y, is Y.name(): Y. Z: Z.print() runs; Z has no name(), the search ends at Y: Z:Y.

X
Y
Z:Y
Example 4.4.12

Problem 7: Removing the instanceof chain. How can the loop with the instanceof chain (Dog → bark, Cat → scratch, other → "No special behavior") be written without any instanceof?

A method void special() is added to Animal and prints "No special behavior". Dog overrides it to call bark(), and Cat to call scratch(). The loop shrinks to a single line:

// in Animal:
void special() { System.out.println("No special behavior"); }
// in Dog:
@Override void special() { bark(); }
// in Cat:
@Override void special() { scratch(); }
// loop:
for (Animal x : animals) {
    x.special();
}

The output is the same three lines. When a new subclass is added, the loop does not change; the new class overrides special() if it wants to, and otherwise gets the default behavior.

Example 4.4.13

Problem 8: A call through an Object reference. Why does Object o = new Dog(); followed by o.makeSound(); not compile? With print(Animal) and print(Dog) present, does print(o) compile?

Object has no makeSound(): cannot find symbol … location: variable o of type Object. The fix: ((Animal) o).makeSound();. Since the object is a dog, it prints Woof woof!.

print(o) does not compile either. The declared type of o is Object, and neither version accepts an Object: no suitable method found for print(Object). With print((Dog) o) it compiles and print(Dog) is chosen.

4.4.8Common mistakes

Mistakes related to polymorphism fall into two groups. Compile errors come from the compiler looking only at the declared type, and their messages are clear. Run-time and logic errors pass the compiler; they show up either as an exception or as silently wrong results. The two tables below gather the mistakes treated separately in the body of these notes. The messages were obtained with the javac and java tools of JDK 21.

Table 4.4.16: Common compile errors related to polymorphism.
Codejavac messageReason / fix
Dog k = new Animal();incompatible types: Animal cannot be converted to DogNot every animal is a dog; the reverse assignment is not possible.
Dog k = animal;incompatible types: Animal cannot be converted to DogEven if the object is a dog, an explicit cast is needed: (Dog) animal.
animal.bark();cannot find symbol … variable animal of type AnimalThe method is not in the reference type; a downcast is needed first.
(Dog) h.bark();not a statementMissing parentheses: ((Dog) h).bark();
(Cat) dogincompatible types: Dog cannot be converted to CatThere is no cast between sibling classes.
@Override void makeSound()method does not override or implement a method from a supertypeThe name is misspelled (upper/lower case).
void makeSound() (public in the superclass)attempting to assign weaker access privileges; was publicAn overriding method cannot narrow access.
show(null) (two unrelated versions)reference to show t ambiguousChosen with an explicit cast: show((Animal) null).
List<Animal> l = new ArrayList<Dog>();incompatible types: ArrayList<Dog> cannot be converted to List<Animal>Generics are not covariant.
Table 4.4.17: Common run-time and logic errors related to polymorphism.
MistakeResultFix
An unchecked downcast: (Dog) h, although h may be a catClassCastExceptionTest with instanceof first.
Thinking “a cast changes the object”((Animal) dog).makeSound() still prints Woof woof!A cast changes only the type that is looked at.
Thinking fields are overridden tooh.kind is read by the reference type: mammalMake the field private and override the getter method.
Mistaking overloading for overriding: equals(Person k)Collections do not call this method; Object.equals runsThe signature becomes equals(Object); @Override catches the mistake.
Comparing objects with ==References are compared, not contentsThe overridden equals is used.
instanceof chains everywhereSilently wrong results as new subclasses are addedThe behavior is moved to an overridden method.
Calling an overridable method from a constructornull output or NullPointerExceptionOnly private, final or static methods are called from a constructor.
Relying on array covariance: Animal[] d = new Dog[2]; d[1] = new Cat();ArrayStoreException: CatThe array is created with the superclass type.
Thinking boxing comes firstf(5) → f(long), not f(Integer)Widening is in phase 1.
Extending equals in a subclass in one direction onlyp.equals(k) true, k.equals(p) falseA getClass() comparison, or composition.

The error equals(Person k) in the table needs a separate explanation. The signature of the method in Object is equals(Object). Writing equals(Person k) in a subclass does not override it; it adds a new overload with the same name. In the call a.equals(b) made with two variables of type Person, the new method is chosen and seems to work correctly. But ArrayList.contains or HashSet pass the argument with type Object. The compiler sees only equals(Object) in that code; since Person does not override it, the reference comparison of Object runs. Had @Override been written on the method, the compiler would say method does not override or implement a method from a supertype and the mistake would have been caught from the start.

4.4.9Summary

  • Polymorphism means that the same expression leads to different behavior in different objects. The code is written once with the superclass type; each object answers the call with its own version.
  • Compile-time polymorphism is provided by overloading, run-time polymorphism by overriding and dynamic binding. The compiler chooses the first, the JVM the second.
  • Every reference variable has a declared type and the actual type of the object it points to. The declared type decides which methods can be called and which assignments are valid; the actual type decides which version runs.
  • The reference rule: a superclass reference can point to a subclass object; the reverse does not compile. Animal h = new Dog(); is valid, Dog k = new Animal(); is an error.
  • Upcasting is automatic and always safe. A downcast is written explicitly; if the object does not fit, ClassCastException is thrown at run time. A cast between sibling classes never compiles.
  • The dot operator is applied before the cast: the correct form is ((Dog) h).bark().
  • instanceof tests the type of the object before the cast. Since Java 16, pattern matching combines the test and the cast: if (x instanceof Dog kk).
  • Arrays are covariant; writing an element of the wrong type gives ArrayStoreException. Generics are not covariant and prevent the same error at compile time.
  • Method lookup starts at the actual class of the object and climbs up. The JVM does this with method tables kept per class, with a single array access; only the method of the reference type is written in the bytecode (invokevirtual).
  • Fields and static, private and final methods are not bound dynamically. A field with the same name or a static method with the same signature in a subclass hides the one in the superclass; it does not override it.
  • An overridable method called from a constructor runs before the subclass's fields are assigned. Only private, final or static methods are called from a constructor.
  • The overloading choice is made at compile time by the declared types of the arguments. If several versions fit, the most specific is chosen; if there is no single most specific version, the call is ambiguous.
  • Overloading is resolved in three phases: without boxing (widening), boxing, variable arity. If a candidate is found in a phase, later ones are not reached; narrowing is never tried.
  • Polymorphic code is open for extension and closed for modification: adding a new subclass changes no existing loops or methods. Parameter and variable types are chosen as the most general type that is enough to do the job.
  • If equals is extended in a subclass in one direction only, symmetry breaks. The solution is a getClass() comparison or composition instead of inheritance.

4.4.10Key terms

  • polymorphism
  • compile time / run time
  • declared type / actual type
  • reference
  • superclass / subclass
  • is-a / has-a relationship
  • Object class
  • upcasting / downcasting
  • cast (explicit conversion)
  • widening / narrowing conversion
  • dynamic binding
  • virtual method table
  • method overriding
  • method overloading
  • method signature
  • autoboxing / unboxing
  • constructor
  • stack trace
  • generics
  • factory method
  • composition
  • abstract method
  • hiding
  • array covariance
  • pattern matching
  • open/closed principle

4.4.11Test Yourself

The questions use the example hierarchy: Dog overrides makeSound() and run(); Cat overrides only makeSound().

  1. What does Animal h = new Cat(); h.run(); h.makeSound(); print?

    Answer

    Animal runs and Meow!. For run() the search starts at Cat; since Cat does not override this method, it ends at Animal. makeSound() is found in Cat.

  2. After Object o = new Cat();, what is the result for each of the lines Animal h = (Animal) o;, Cat c = (Cat) o;, Dog k = (Dog) o; and Cat c2 = o;?

    Answer

    The first three lines compile; a downcast from Object to any class can be written. At run time the first two succeed, because the object is a cat and a cat is an animal. The third gives ClassCastException. The fourth line does not compile at all: there is no explicit cast (incompatible types: Object cannot be converted to Cat).

  3. Given class U { int x = 1; int getX() { return x; } } and class V extends U { int x = 2; int getX() { return x; } }. What does u.x + " " + u.getX() + " " + ((V) u).x give for U u = new V();?

    Answer

    1 2 2. u.x is a field access and is read by the declared type (U): 1. u.getX() is bound dynamically; the x inside V.getX() is the field of V: 2. After the cast the declared type is V: 2.

  4. Let static void g(Object o) print "O" and static void g(String s) print "S". For Object a = "x";, what do g(a), g((String) a) and g(null) print?

    Answer

    O, S, S. The declared type of a is Object; that the object is a string does not matter. With the cast the type becomes String. null fits both versions; but String is a subtype of Object and the two candidates lie on a single chain. The more specific g(String) is chosen; there is no ambiguity.

  5. With static void h(double d) and static void h(Integer i) present, which version do h(5), h(Integer.valueOf(5)) and h(5L) choose?

    Answer

    h(5): in phase 1 the widening int → double fits; Integer needs boxing and is not tried: double. h(Integer.valueOf(5)): in phase 1 the exact match is h(Integer); reaching double needs unboxing: Integer. h(5L): long widens to double: double.

  6. Given class A { A() { m(); } void m() { System.out.println("A"); } } and class B extends A { int n = 7; void m() { System.out.println("B " + n); } }. What does new B(); print?

    Answer

    B 0. The call m() inside A() is bound dynamically, and since the object is a B, B.m() runs. At that moment n has not yet been given its initial value; the default value of int is 0. n = 7 runs after A() returns.

  7. Which of the lines Object[] d = new Integer[2]; d[0] = 5; d[1] = "a"; causes a problem?

    Answer

    All three lines compile. d[0] = 5 works: 5 is boxed to Integer and fits the actual element type of the array. d[1] = "a" gives ArrayStoreException: java.lang.String at run time; the array is really an Integer[].

  8. Given class P { String name() { return "P"; } String print() { return name(); } } and class Q extends P { String name() { return "Q"; } String print() { return "[" + super.print() + "]"; } }. What does p.print() return for P p = new Q();?

    Answer

    [Q]. p.print() is bound dynamically: Q.print(). super.print() calls P.print() directly (invokespecial). The name() inside it is this.name(), and this is still a Q object: Q.name() → "Q". super fixes only the target of that one call; the calls inside are still bound dynamically.

4.4.12Further reading

  • Oracle, The Java Tutorials, the “Polymorphism” and “Overriding and Hiding Methods” pages: explain dynamic binding and the hiding of fields and static methods with short examples. It is Java's official, free starting point.
  • J. Bloch, Effective Java (3rd ed.), Item 10 “Obey the general contract when overriding equals” and Item 19 “Design and document for inheritance or else prohibit it”: discuss in detail the equals symmetry trap and the danger of calling an overridable method from a constructor.
  • P. Deitel and H. Deitel, Java: How to Program (11th ed.), Chapter 10 “Object-Oriented Programming: Polymorphism and Interfaces”: builds up polymorphism step by step with a payroll example; it also moves on to abstract classes and interfaces.
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition, 5.5 “Casting Contexts” and 15.12 “Method Invocation Expressions”: the exact definition of casts and of the three phases of overload resolution.

4.4.13References

  1. Oracle, The Java Tutorials: “Polymorphism”; “Overriding and Hiding Methods”; “Inheritance”.
  2. J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Oracle, 2023 (5.5 Casting Contexts; 8.4.8 Inheritance, Overriding, and Hiding; 15.12 Method Invocation Expressions).
  3. P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapter 10: Object-Oriented Programming: Polymorphism and Interfaces).
  4. K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly, 2022 (Inheritance and Polymorphism).
  5. C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson, 2022 (Chapter 5: Inheritance).
  6. A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019.
  7. J. Bloch, Effective Java, 3rd ed., Addison-Wesley, 2018.

Related pages: Chapter 4.4 slides · Study questions · Dynamic Dispatch simulator · Glossary · © Sercan Külcü. All rights reserved.