Chapter 4.4: Polymorphism

Object Oriented Programming with Java
What polymorphism isThe reference ruleUpcasting and downcastinginstanceof Dynamic bindingMethod tablesOverloadingShape and anti-tank examplesequals and symmetry
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Concept

Define polymorphism and distinguish compile-time from run-time polymorphism.

The reference rule

Explain why a superclass reference can hold a subclass object, and why the reverse is a compile error.

Type conversion

Write upcasts and downcasts; prevent ClassCastException with instanceof.

Dynamic binding

Trace step by step how the method called is chosen by the object's actual class; show the method lookup in the hierarchy.

Overloading vs. overriding

Compare overloading with overriding; know which one the compiler picks and which one the JVM picks.

Design

Write general code against a superclass type, using a shape array and an anti-tank game; recognize the symmetry trap in equals.

The Idea of Polymorphism

Polymorphism

  • Greek poly (many) + morph (form): the same expression leads to different behavior on different objects.
  • A reference can refer to an object of its own type or of any subclass.
  • animal.makeSound() prints Woof woof! for a dog and Meow! for a cat.
  • We write the code once, against the superclass; each object answers the call with its own version.
The four pillars of object-oriented programming: encapsulation, inheritance, polymorphism and abstraction. Polymorphism is built on inheritance.
Remote controlThe same "on" button turns on the TV, the air conditioner and the projector; each device does it in its own way.
Driver's licenseOne license lets you drive any make of car: the driver uses the "car" interface; the engine details belong to the maker.
ZooThe keeper says "everyone, make a sound"; each animal makes its own.

The Idea of Polymorphism

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 checked?Number and declared types of the argumentsThe object's actual class
Needs inheritance?No, works within one classYes, needs a class hierarchy

Same name, different parameters

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

sum(5, 3);       // int version
sum(3.5, 2.7);   // double version

Same signature, different classes

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

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

"Polymorphism" usually means run-time polymorphism.

The Idea of Polymorphism

Example Class Hierarchy

Object+toString(): String+equals(Object): boolean+getClass(): ClassAnimal+makeSound(): void+run(): void+sleep(): voidDog+makeSound(): void+run(): void+bark(): voidCat+makeSound(): void+scratch(): void
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"); }
}
  • Dog overrides makeSound() and run() and adds bark(); Cat overrides only makeSound() and adds scratch().
  • Dog and Cat are both Animals (is-a); either can be stored in a variable of type Animal.

References and Type Compatibility

A Reference Can Point to a Subclass Object

// 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());
Reference variablesObject on the heapdogtype: DogDog objectObject partAnimal partDog part

new Dog() creates one object on the heap; the dog reference points to it.

Reference variablesObject on the heapdogtype: Doganimaltype: AnimalDog objectObject partAnimal partDog part

No new object is created: animal is a second reference to the same object. A Dog is an Animal, so the assignment is legal.

Reference variablesObject on the heapdogtype: Doganimaltype: Animalobjtype: ObjectDog objectObject partAnimal partDog part

Every class extends Object, so an Object reference can point to the same object too.

Reference variablesObject on the heapdogtype: Doganimaltype: Animalobjtype: ObjectDog objectObject partAnimal partDog part

== compares references: both point to the same object, so true.

Reference variablesObject on the heapdogtype: Doganimaltype: Animalobjtype: ObjectDog objectObject partAnimal partDog part

Still the same object: true. Three references, one object.

Reference variablesObject on the heapdogtype: Doganimaltype: Animalobjtype: ObjectDog objectObject partAnimal partDog part

The reference type is Object, but the object's actual class does not change: Dog.

References and Type Compatibility

Reference Type vs. Object Type

Animal hreferenceDog objecton the heapdeclared typecompiler looksactual typeJVM looks
Animal h = new Dog();
// declared type: Animal
// actual type:   Dog
QuestionWho decides?
Can this method be called?The compiler, from the reference type
Which version runs?The JVM, from the object type
Which assignments are legal?The compiler checks the reference type
Animal animal = new Dog();
animal.bark(); // compile error
error: cannot find symbol
  symbol:   method bark()
  location: variable animal of type Animal

You can't use a feature with no button on the remote: the object may be a dog, but the Animal "remote" has no bark() button.

References and Type Compatibility

The Reference Rule

  • An object of a subclass can be assigned to a reference of the superclass type.
  • But a superclass object cannot be assigned to a reference of the subclass type.

Legal

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

Every dog is an animal: a dog can do everything expected of an animal.

Illegal

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

An animal may not know bark(); the compiler won't allow it.

Animal h = new Dog(); Dog k = h; gives the same error. The compiler sees the h reference's declared type (Animal), not the object it points to; the fix is an explicit cast.
Animal hDog object✓ legalDog kAnimal object✗ won't compile

Type Conversion

Upcasting and Downcasting

AnimalDogupautomaticdownwith (Dog)
UpcastingDowncasting
DirectionSub → superSuper → sub
SyntaxAutomatic (implicit)Explicit: (Dog) h
Safe?AlwaysDepends on the object
Also calledWideningNarrowing
Dog dog = new Dog();
Animal h = dog;    // up: automatic
Animal h1 = (Animal) dog; // unnecessary
Animal h = new Dog();
Dog k = (Dog) h; // down: explicit
k.bark();        // Dog barks

Type Conversion

Downcasting

  • A superclass reference can be explicitly converted to a subclass type: (Subclass) reference.
  • Only through such a cast can a superclass reference be assigned to a subclass variable.
  • Purpose: to call methods that are not in the superclass (that belong only to the subclass).
  • A cast does not change the object; it only tells the compiler "treat this reference as a Dog".
Animal h2 = new Dog();
Dog k = (Dog) h2;
k.bark();
((Dog) h2).bark(); // in one line
Dog barks
Dog barks

Precedence trap

The dot (.) binds tighter than a cast. Without parentheses, (Dog) is applied to the result of bark():

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

Correct: ((Dog) h2).bark();

Type Conversion

Bad Downcast: ClassCastException

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
Dog k5 = (Dog) new Animal(); // compiles!
java.lang.ClassCastException:
class Animal cannot be cast to class Dog
  • The compiler allows it: a reference of type Animal may well point to a Dog.
  • The JVM checks the object's actual class at the cast: if it is a Cat or a plain Animal, the program stops with an exception.
  • So a superclass object can never be assigned to a subclass reference; a cast only succeeds if the object really is of that subclass.
B objB = (B) objA; compiles, but runs only if objA really points to a B object. If unsure, test it first with instanceof.

Casts between unrelated types are rejected outright: (Cat) dog → incompatible types: Dog cannot be converted to Cat.

Type Conversion · Step-by-step code trace

ClassCastException: Code Trace

StackHeapmain()h1Dog #1

Upcast: h1, of type Animal, points to a Dog object.

StackHeapmain()h1h2Dog #1Cat #2

h2 points to a Cat. To the compiler both are just Animal.

StackHeapmain()h1h2k1Dog #1Cat #2JVM check: object's classDog = Dog ✓

The compiler allows the cast. At run time the JVM checks the object: it really is a Dog. k1 points to the same object.

StackHeapmain()h1h2k1Dog #1Cat #2

Through a Dog reference, bark() can be called.

StackHeapmain()h1h2k1k2?Dog #1Cat #2JVM check: is a Cat a Dog?CatAnimalObject ✗

This line compiles too. But going up the chain from Cat, the JVM finds no Dog.

StackHeapmain()h1h2k1k2?Dog #1Cat #2ClassCastException → lines 6 and 7 never run

ClassCastException is thrown and nothing is assigned to k2; with no handler the program stops, and Done is never printed.

Animal h1 = new Dog();
Animal h2 = new Cat();
Dog k1 = (Dog) h1;
k1.bark();
Dog k2 = (Dog) h2;
k2.bark();
System.out.println("Done");

Type Conversion

instanceof for Safe Casting

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
  • reference instanceof Type: true if the object is a Type or a subclass of it.
  • Test first, then cast: no ClassCastException can occur. null instanceof Type is always false.

Java 16+: pattern matching

if (x instanceof Dog kk) {
    kk.bark(); // cast is automatic
}
Long instanceof chains are usually a design smell: it is better to move the behavior into a method overridden in the subclasses (Exercise 5).

Type Conversion · Step-by-step code trace

instanceof for Safe Casting: Code Trace

arr•••Cat #1Animal #2Dog #3

All three elements are references of type Animal; the objects they point to are of different classes.

arr•••Cat #1Animal #2Dog #3x→ Cat #1x instanceof Dogfalse

First iteration: x is a Cat. The Dog test is false.

arr•••Cat #1Animal #2Dog #3x→ Cat #1x instanceof Dogfalsex instanceof Cattrue

The Cat test is true; since it was tested first, the cast (Cat) x is safe: Cat scratches.

arr•••Cat #1Animal #2Dog #3x→ Animal #2x instanceof Dogfalsex instanceof Catfalse

Second iteration: a plain Animal. Not an instance of any subclass: both tests are false.

arr•••Cat #1Animal #2Dog #3x→ Animal #2x instanceof Dogfalsex instanceof Catfalse

The else branch runs; no cast is attempted, so no risk.

arr•••Cat #1Animal #2Dog #3x→ Dog #3x instanceof Dogtrue

Third iteration: the Dog test is true and bark() runs. The loop ends; no ClassCastException was thrown in any iteration.

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");
    }
}

Type Conversion

Arrays and ArrayStoreException

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

Same idea with a generic list

List<Animal> l = new ArrayList<Dog>();
error: incompatible types: ArrayList<Dog>
  cannot be converted to List<Animal>
  • Arrays are covariant: a Dog is an Animal, so a Dog[] also counts as an Animal[] and the upcast compiles.
  • But the array object is really a Dog[]. Storing a Cat in it through the Animal[] reference looks fine to the compiler; the JVM checks the element type on every store and throws ArrayStoreException.
  • Generic collections close this hole at compile time: a List<Dog> is not a List<Animal>.
  • Covariance is safe for reading (every element is an Animal); the problem only arises when writing.

Dynamic Binding

Dynamic Binding

  • If the reference points to a subclass object, the subclass's method is called.
  • The version called depends not on the variable's declared type but on the object's actual class.
  • The choice is made not at compile time but at run time, hence dynamic (late) binding.
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

h.run() is resolved in two steps

1. Compile timeThe compiler looks at h's type (Animal): does it have run()? Yes → the call compiles. Otherwise, a compile error.
2. Run timeThe JVM looks at the object: its actual class is Dog → Dog.run() runs.
Rule: the compiler asks "is there one?"; the JVM asks "which one?".
h.run()Compiler: does Animal have run()?yes → compiles (else error)JVM: what class is the object?Dog → Dog.run() runs

Dynamic Binding

Method Lookup Starts at the Bottom of the Hierarchy

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(): voidDog+makeSound(): void+run(): void+bark(): voidactual class

The object is a Dog: lookups always start at the bottom, at the actual class.

Object+toString(): String+equals(Object): booleanAnimal+makeSound(): void+run(): void+sleep(): voidDog+makeSound(): void+run(): void+bark(): void✓ found

Dog has run() → lookup ends, the Dog version runs.

Object+toString(): String+equals(Object): booleanAnimal+makeSound(): void+run(): void+sleep(): void✓ foundDog+makeSound(): void+run(): void+bark(): void✗ not here, go up

Dog has no sleep() → go up one level: found in Animal.

Object+toString(): String+equals(Object): boolean✓ foundAnimal+makeSound(): void+run(): void+sleep(): void✗ not hereDog+makeSound(): void+run(): void+bark(): void✗ not here

toString() is found at the top, in Object: class name + @ + hex hash code (varies between runs).

Object+toString(): String+equals(Object): booleanAnimal+makeSound(): void+run(): void+sleep(): void✗ no bark()Dog+makeSound(): void+run(): void+bark(): void

h.bark() does not compile: the compiler searches up from the reference type Animal and finds nothing.

Dynamic Binding

Polymorphic Array: Step-by-Step Trace

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();
}
animalsheap0null1null2null

Animal array of 3: the elements are references, initially null.

animalsheap0Dog object1null2null

Element 0 points to a Dog (upcast, automatic).

animalsheap0Dog object1Cat object2null

Element 1 points to a Cat.

animalsheap0Dog object1Cat object2Animal object

Element 2 is a plain Animal object. The array now holds three different forms.

animalsheap0Dog object1Cat object2Animal object

i = 0, 0 < 3 true → loop body.

animalsheap0Dog object1Cat object2Animal object

Same line, different object: the JVM checks the object's class → Dog.makeSound().

animalsheap0Dog object1Cat object2Animal object

i = 1, 1 < 3 true → loop body.

animalsheap0Dog object1Cat object2Animal object

Same line, different object: the JVM checks the object's class → Cat.makeSound().

animalsheap0Dog object1Cat object2Animal object

i = 2, 2 < 3 true → loop body.

animalsheap0Dog object1Cat object2Animal object

Same line, different object: the JVM checks the object's class → Animal.makeSound().

animalsheap0Dog object1Cat object2Animal object

i = 3, 3 < 3 false → the loop ends. One line of code, three behaviors.

Dynamic Binding

Behind the Scenes: The Method Table

  • JVMs usually implement dynamic binding with a per-class method table (virtual method table): each overridable method has a fixed index (slot).
  • A subclass's table starts as a copy of its superclass's; overridden slots are replaced with the new body, and new methods are appended.
  • Every object knows its class. For h.run() the JVM goes object → class → the table's run slot → body. The lookup is one array access; no walking up the hierarchy.

javap -c Main output

47: invokevirtual #15  // Method Animal.run:()V
52: invokevirtual #18  // Method Animal.makeSound:()V
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: classholding the bodyhighlighted: bodywritten in this classfaded: copied from above

The compiler writes only Animal.run into the bytecode; invokevirtual picks the body from the object's table. Constructors and super.m() use invokespecial, static methods use invokestatic: no table lookup. private methods use invokevirtual since Java 11, but have only one candidate.

Dynamic Binding · Step-by-step code trace

Calls via the Method Table: Code Trace

HeapDog #1class →Cat #2class →Dog tableCat tableeach object linksto its class, and theclass to its tabled[0] and d[1]: both Animal references

The two objects in the array belong to different classes; each carries a link to its own class's table.

Stackhmain()Dog #1class →Dog table[0] makeSoundDog[1] runDog[2] sleepAnimal[3] barkDoginvokevirtual Animal.run → slot [1]Dog table [1] = Dog.run

The bytecode says “Animal.run, slot 1”. The object is a Dog: slot 1 of its table holds Dog.run.

Stackhmain()Dog #1class →Dog table[0] makeSoundDog[1] runDog[2] sleepAnimal[3] barkDoginvokevirtual Animal.makeSound → slot [0]Dog table [0] = Dog.makeSound

Same path, slot 0: Woof woof!

Stackhmain()Cat #2class →Cat table[0] makeSoundCat[1] runAnimal[2] sleepAnimal[3] scratchCatinvokevirtual Animal.run → slot [1]Cat table [1] = Animal.run (inherited)

Same bytecode, different object. Cat does not override run, so slot 1 of its table points to Animal.run.

Stackhmain()Cat #2class →Cat table[0] makeSoundCat[1] runAnimal[2] sleepAnimal[3] scratchCatinvokevirtual Animal.makeSound → slot [0]Cat table [0] = Cat.makeSound

Slot 0 again: Meow! None of the four calls used if or a type test: the tables made the choice.

Animal[] d = {new Dog(), new Cat()};
for (Animal h : d) {
    h.run();
    h.makeSound();
}

Dynamic Binding

What Is Not Dynamically Bound?

class Animal {
    String kind = "animal";

    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);
    }
}
Animal h = new Dog();
System.out.println(h.kind);
h.info();
h.introduce();
animal
Animal.info()
I am a dog
MemberChosen by
Instance methodObject type (dynamic)
FieldReference type (static)
static methodReference type (static)
private / finalCannot be overridden; static

Call a static method through the class name: Dog.info(). Avoid declaring a field with the same name in a subclass.

Dynamic Binding · Step-by-step code trace

Field Hiding and static: Code Trace

StackHeapmain()hDog #1Animal.kind"animal"Dog.kind"dog"one object, two separate kind fields

The subclass's kind does not override the superclass's, it hides it: the object has two separate fields.

StackHeapmain()hDog #1Animal.kind"animal"Dog.kind"dog"field → declared type (Animal)

Fields are not dynamically bound: h's declared type is Animal, so Animal.kind is read: animal.

StackHeapmain()hDog #1Animal.kind"animal"Dog.kind"dog"static method → declared type; object ignored

static methods belong to the class; the compiler binds h.info() to Animal.info().

StackHeapDog.introduce()thismain()hDog #1Animal.kind"animal"Dog.kind"dog"instance method → actual type (Dog)

Instance methods are dynamically bound: Dog.introduce() runs, and inside it kind is Dog's field: I am a dog.

StackHeapmain()hDog #1Animal.kind"animal"Dog.kind"dog"(Dog) h → reads Dog.kind

The cast makes the declared type Dog; the object's other field is read: dog. Because of this confusion, subclasses should not declare a field with the same name.

class Animal {
    String kind = "animal";
    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);

Dynamic Binding

Calling an Overridable Method from a Constructor

  • Dynamic binding works even while the object is being constructed: the object is a Label, so the draw() call in the superclass constructor runs Label.draw().
  • But at that moment the subclass field initializers have not run yet: text is still null. The subclass method runs on a half-built object.
  • Had the method used the field rather than just printing it, the program would have crashed.
  • Rule: call only private, final or static methods from a constructor; they cannot be overridden.

If draw() used text.length()

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)
The stack trace tells the story: Label constructor → Component constructor → back to Label's method. <init> is the constructor's name in bytecode.

Dynamic Binding · Step-by-step code trace

Call in a Constructor: Code Trace

StackHeapLabel()main()e?Label #1textnullobject allocated; Label() → implicit super()

new allocates the object; text is null by default. The first thing Label() does is the implicit super() call.

StackHeapComponent()Label()main()e?Label #1textnullbuilding the superclass part

Component()'s body prints the first line.

StackHeapLabel.draw()Component()Label()main()e?Label #1textnullLabel.draw() chosen, text = null

draw() = this.draw(). The object's class is Label, so the overridden version is chosen; but text is not assigned yet: Label: null.

StackHeapLabel()main()e?Label #1text"Hello"super() returned → field initializers

After the superclass constructor returns, the subclass field initializer runs: text = "Hello". Too late: draw() was already called.

StackHeapLabel()main()e?Label #1text"Hello"Label() body

The Label() body runs; the object is now built.

StackHeapLabel.draw()main()eLabel #1text"Hello"same method, built object

On a fully built object the same method gives the right result. The only difference is when the call is made.

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();

Overloading

Overloading 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)
  • animal points to a Dog, yet print(animal) → print(Animal).
  • The compiler picks among overloads by the argument's declared type.
  • A cast changes the declared type: (Dog) animal → print(Dog).
OverloadingOverriding
Where?Same classSubclass
SignatureDifferent parametersSame signature
Chosen atThe compilerThe JVM
Based onDeclared typeActual type

Overloading

Overloading: Most Specific Version and Ambiguity

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)

show(null);

error: reference to show is ambiguous
  both method show(Animal) in Main and
  method show(String) in Main match
  • If several versions apply, the compiler picks the most specific one: Cat fits both Animal and Object; Animal is more specific.
  • null fits every reference type. Animal and String are not related by inheritance, so neither is more specific: an ambiguous call, a compile error.
  • If the applicable versions lie on one chain (Object, Animal, Cat) there is no ambiguity: show(null) picks the lowest, show(Cat).
  • The fix is to set the declared type with an explicit cast: show((Animal) null).

Overloading · Step-by-step code trace

Compiler or JVM? Code Trace

The compilerlooks at declared typeThe JVMlooks at object's classprint(Animal)print(Dog)Dog.makeSound()Cat.makeSound()compile timerun time

Both variables have the same declared type (Animal); the objects differ: Dog and Cat.

The compilerlooks at declared typeThe JVMlooks at object's classargument type: Animalprint(Animal)print(Dog)Dog.makeSound()Cat.makeSound()compile timerun time

animal points to a Dog, but the compiler knows only the declared type: print(Animal).

The compilerlooks at declared typeThe JVMlooks at object's classargument type: Animalprint(Animal)print(Dog)object: DogDog.makeSound()Cat.makeSound()compile timerun time

Inside the method, h.makeSound() is an overridden method: the JVM looks at the object: Woof woof!

The compilerlooks at declared typeThe JVMlooks at object's classargument type: Animalprint(Animal)print(Dog)Dog.makeSound()Cat.makeSound()compile timerun time

other is also of type Animal: the same version is chosen.

The compilerlooks at declared typeThe JVMlooks at object's classargument type: Animalprint(Animal)print(Dog)object: CatDog.makeSound()Cat.makeSound()compile timerun time

Same line, different object: this time Cat.makeSound(), Meow!

The compilerlooks at declared typeThe JVMlooks at object's classargument type: Dogprint(Animal)print(Dog)Dog.makeSound()Cat.makeSound()compile timerun time

The explicit cast makes the declared type Dog: this time the compiler picks print(Dog).

The compilerlooks at declared typeThe JVMlooks at object's classargument type: Dogprint(Animal)print(Dog)object: DogDog.makeSound()Cat.makeSound()compile timerun time

Overload resolution used the declared type at compile time; override selection used the actual type at run time.

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

Overloading

The Three Phases of Overload Resolution

1. No boxing

Only exact matches, primitive widening (int → long) and reference widening (String → Object) are tried.

2. Boxing

If phase 1 finds no candidate, boxing and unboxing are tried too: double → Double → Object.

3. Varargs

If there is still no candidate, variable-arity versions such as int... come into play.

  • Once a phase finds at least one candidate, later phases are skipped; the most specific candidate of that phase wins.
  • Result: given f(long) and f(Integer), the call f(5) picks f(long). Widening comes before boxing because boxing arrived in Java 5, and old programs had to keep their behavior.
  • Narrowing (long → int) is never tried; if no phase finds a candidate: no suitable method found for print(boolean).
  • This order is applied at compile time; the chosen signature goes into the bytecode. Which class's body runs for that signature is decided at run time.

Overloading · Step-by-step code trace

Overload Phases: Code Trace

Argument: 5 (int)1. no boxing2. boxing3. varargsf(long)✓ int → long wideningf(Integer)✗ needs boxingf(Object)✗ needs boxingf(int...)phase 1 has one candidate: f(long)

5 is an int. In phase 1 only long fits, by widening; Integer and Object need boxing and are not tried in this phase.

Argument: b (byte)1. no boxing2. boxing3. varargsf(long)✓ byte → long wideningf(Integer)✗ Byte ≠ Integerf(Object)✗ needs boxingf(int...)f(long) again

byte also widens to long. Even boxed it would be a Byte, not an Integer.

Argument: Integer1. no boxing2. boxing3. varargsf(long)✗ needs unboxingf(Integer)✓ exact matchf(Object)✓ Integer → Objectf(int...)two candidates: Integer is most specific

The argument is already an Integer: phase 1 has two candidates. Integer is more specific than Object, so it wins.

Argument: "x" (String)1. no boxing2. boxing3. varargsf(long)✗f(Integer)✗f(Object)✓ String → Objectf(int...)reference widening: f(Object)

A String fits only Object.

Argument: 2.5 (double)1. no boxing2. boxing3. varargsf(long)✗ double → long narrowingf(Integer)✗ Double ≠ Integerf(Object)✓ double → Double → Objectf(int...)phase 1 empty → boxing in phase 2

A double cannot be narrowed to long; phase 1 has no candidate. In phase 2 it is boxed to Double, which fits Object.

Argument: () and (1, 2)1. no boxing2. boxing3. varargsf(long)✗ parameter countf(Integer)✗ parameter countf(Object)✗ parameter countf(int...)✓ 0 or 2 intsonly phase 3 has a candidate

Zero or two arguments fit only int...; it is tried last, in phase 3.

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

Inheritance and Polymorphism

Inheritance and Polymorphism

  • Inheritance is needed to build class hierarchies.
  • Polymorphism requires inheritance: we need a class hierarchy.
  • Inheritance does not require polymorphism: we can inherit just to reuse code.
  • If B is a subclass of A, a B object can act as an A object (not the reverse).
  • Assigning an A reference to a B reference needs a narrowing conversion (cast), written with parentheses.
A objA = new B(); // B acts as an A
B objB = (B) objA; // legal, but
                   // use with care
The last line compiles; at run time, if objA does not point to a B object, a ClassCastException is thrown.

Interfaces also provide polymorphism in Java: any class that implements an interface can be assigned to a reference of that interface type.

A objAB object(B) objA → ✓ succeedsA objAA object(B) objA → ✗ ClassCastException

Inheritance and Polymorphism

Example: Shape Hierarchy

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()
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.");
    }
}

abstract: a method with no body; every subclass must implement it, and new Shape(…) is not allowed.

Inheritance and Polymorphism

Subclasses Override the Methods

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);
    }
}

Square: the constructor passes the name up with super("Square"); it overrides all three methods.

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 not draw() → Shape.draw() is used.

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 with Math.PI; overrides draw() with its own info.

Inheritance and Polymorphism

Shape Array: Step-by-Step Trace

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();
}
shapesheap0Square (5)1Rectangle (4, 6)2Circle (7)

The array is of type Shape; its elements point to objects of three different subclasses.

shapesheap0Square (5)1Rectangle (4, 6)2Circle (7)

shape.area() → Square.area() runs.

shapesheap0Square (5)1Rectangle (4, 6)2Circle (7)

draw() overridden → Square.draw() runs.

shapesheap0Square (5)1Rectangle (4, 6)2Circle (7)

shape.area() → Rectangle.area() runs.

shapesheap0Square (5)1Rectangle (4, 6)2Circle (7)

Rectangle does not override draw() → lookup goes up, Shape.draw() runs.

shapesheap0Square (5)1Rectangle (4, 6)2Circle (7)

shape.area() → Circle.area() runs.

shapesheap0Square (5)1Rectangle (4, 6)2Circle (7)

draw() overridden → Circle.draw() runs.

Inheritance and Polymorphism

Why Polymorphism?

With type tests

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;
}

Every new shape means changing this method; forget it and badArea(new RightTriangle(3, 4)) silently returns 0.0.

Polymorphic

static double totalArea(Shape[] arr) {
    double total = 0;
    for (Shape shape : arr) {
        // each object knows its area
        total += shape.area();
    }
    return total;
}
  • Just add a new RightTriangle extends Shape class; this code never changes.
  • { Square(5), Rectangle(4, 6), RightTriangle(3, 4) } → 55.0
  • Shorter code, and no ClassCastException risk.

Principle: open for extension, closed for modification (open/closed principle).

Inheritance and Polymorphism

Polymorphic 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
  • Parameter of superclass type: the method accepts objects of every subclass, existing or yet to be written. examine needs no change for a new Bird class.
  • Return type of superclass type: the method hides which subclass it creates. The caller relies only on the Animal contract; if adopt starts returning another subclass, client code is unaffected.
  • Methods that create objects like this are called factory methods.
  • General rule: choose the most general type for parameters and variables that still does the job.

Inheritance and Polymorphism

Example: Anti-Tank Game

AntiTankx, y: intcolor: Color+fire(): ShellAT Javelin+fire(): ShellAT Tow2A+fire(): ShellShellpos: Rectanglecolor: ColorShell37mmShell57mm

AT Javelin: AntiTankJavelin, AT Tow2A: AntiTankTow2A. Tank also has subclasses TankT90MS and TankLeopard2A4.

  • In this Swing game you shoot falling tanks; every multiple of 10 points switches the anti-tank weapon.
  • 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);
}

Test output

Shell t1 = weapon.fire(); // Javelin
// → Shell37mm, height 30
weapon = new AntiTankTow2A(100, 540);
Shell t2 = weapon.fire();
// → Shell57mm, height 40
The same fire() call yields a different shell when the weapon changes; the game code needs no if.

Inheritance and Polymorphism

equals and Inheritance: The Symmetry Trap

Object methods are dynamically bound too: Object o = k1; System.out.println(o); runs the object's own toString, and o.equals(x) its own equals.

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 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 decides which equals runs: p.equals(k) runs Point's, k.equals(p) runs ColoredPoint's.
  • The results differ: symmetry is broken. A HashSet or contains may answer differently depending on the order of elements.
  • Fixes: compare getClass() in both classes; or use composition instead of inheritance (ColoredPoint holds a Point field).

Summary

Summary

ConceptRuleExample
The reference ruleA superclass reference can point to a subclass object; the reverse won't compileAnimal h = new Dog();
is-aA subclass object is a superclass object; not the reverseh instanceof Animal → true
UpcastingAutomatic and always safeObject o = dog;
DowncastingExplicit; if the object doesn't fit, ClassCastExceptionDog k = (Dog) h;
AccessThe reference type decides which methods can be calledh.bark() → compile error
Dynamic bindingThe object type decides which version runs; lookup goes bottom-uph.run() → Dog version
Static bindingFields, static/private/final methods and overload selectionh.kind → "animal"
BenefitCode written once against the superclass works unchanged with new subclassestotalArea(shapes)

Summary

Related Pages

Abstract Classes and Interfaces

Defining interfaces and implements, polymorphism through interface references, multiple interfaces, default/static/private interface methods, generics.

Link to interfaces

A class can extend only one superclass but implement many interfaces: the same dynamic binding works with interface types, e.g. SoundMaker s instead of Animal h.

Summary

Common Mistakes (1): Compile Errors

CodeCompiler messageCause / fix
Dog k = new Animal();incompatible types: Animal cannot be converted to DogNot every animal is a dog; the reverse assignment is illegal.
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 reference type has no such method; downcast 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 supertypeName misspelled (case matters).
void makeSound() (super: public)attempting to assign weaker access privileges; was publicAn overriding method cannot reduce access.

Summary

Common Mistakes (2): Run Time and Logic

Unchecked downcast

Writing (Dog) h and forgetting that h may point to a Cat → ClassCastException. Test with instanceof first.

Thinking "a cast changes the object"

(Animal) dog does not turn the dog into an animal; makeSound() still prints "Woof woof!".

Thinking fields are overridden too

h.kind is read by the reference type ("animal"). Fix: make fields private and override a getter instead.

Confusing overloading with overriding

Writing equals(Person p) in a subclass does not override equals(Object), it overloads it; collections never call this method. @Override catches this mistake.

== to compare objects

== compares references; for content, use the overridden equals.

instanceof chains everywhere

They break as subclasses are added. Move the behavior into an overridden method.

Summary

Common Mistakes (3)

Calling an overridable method from a constructor

The subclass method runs on an object whose fields are not yet set: null output or NullPointerException.

Relying on array covariance

Animal[] d = new Dog[2]; d[1] = new Cat(); compiles, but at run time: ArrayStoreException: Cat.

Ambiguous call with null

show(null), with two unrelated overloads: reference to show is ambiguous. Resolve it with an explicit cast.

Thinking boxing comes first

With f(long) and f(Integer), f(5) → f(long): widening is in phase 1.

Extending equals one-way in a subclass

p.equals(k) true, k.equals(p) false: symmetry breaks, collections behave inconsistently.

Treating a generic list like an array

List<Animal> l = new ArrayList<Dog>(); → incompatible types. Generics are not covariant.

Summary

Sample Problem 1: What Is the Output?

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();

call() is defined only in A and calls print(). B overrides only print(). What does the program print?

Answer
B.print
A.print
  • a.call(): B has no call → A.call() runs.
  • The inner print() is really this.print(); this is a B object → dynamic binding picks B.print().
  • new A().call(): the object is an A → A.print().
  • Lesson: superclass code may unknowingly call a method the subclass overrides.

Summary

Sample Problem 2: Does It Compile? Does It Run?

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)

For each line decide: compile error, run-time error or fine (with output).

Answer
#ResultReason
1CompileAnimal → Cat needs an explicit cast
2FineThe object really is a Cat
3Run timeClassCastException: Cat → Dog fails
4CompileAnimal has no scratch()
5Fine"Cat scratches"
6CompileObject has no makeSound()
7Fine"Woof woof!" (dynamic binding)

Summary

Sample Problem 3: Overloading + Overriding

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");

Parent has two overloaded f methods; Child overrides only f(Object). What do the two calls print?

Answer
Child.f(Object)
Parent.f(String)
  1. The compiler picks the version: o's declared type is Object → f(Object). At run time the object is a Child → overridden version: Child.f(Object).
  2. Argument String → best version f(String). Child doesn't override it, so Parent.f(String).

Overloading first (compile time, declared type), then overriding (run time, object type).

Summary

Sample Problem 4: Construction, Phases, Arrays

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);
    }
}
  1. new Child(); and then new Child().show(); print what?
  2. Given f(long), f(Integer), f(Object) and f(int...), which versions do short s = 3; f(s);, f('A'); and f(Long.valueOf(4)); choose?
  3. Object[] d = new String[1]; d[0] = 1;: compiles? runs?
Show answers
  1. no arr, then no arr and length 3: during every new Child(), Parent() calls Child.show() before arr is assigned; after construction arr is ready.
  2. f(long), f(long), f(Object): short and char widen to long. For Long, f(long) needs unboxing; the only phase-1 candidate is Object.
  3. Compiles, but at run time ArrayStoreException: java.lang.Integer: 1 is boxed to Integer and cannot be stored in an array that is really a String[].

Summary

Exercises (1)

  1. Write Employee (salary() = base salary), Manager (base × 1.5) and Intern (fixed 5000). For Employee[] = { Ayşe 20000, Manager Mehmet 30000, Intern Can }, what is the total salary?
  2. X: name() → "X", print() → println(name()). Y extends X: name() → "Y". Z extends Y: print() → println("Z:" + name()). What is printed if print() is called on each of { new X(), new Y(), new Z() }?
  3. Object o = new Dog(); followed by o.makeSound();: why doesn't it compile? How do you fix it, and what does it print then?
Answers / hints
  1. Manager.salary() is overridden with return baseSalary * 1.5;; in the loop total += c.salary(); → 20000 + 45000 + 5000 = 70000.0.
  2. X, Y, Z:Y. In Y, print() comes from X but the name() inside it is Y's; in Z, name() comes from Y.
  3. Object has no makeSound() (cannot find symbol). ((Animal) o).makeSound(); → Woof woof!

Summary

Exercises (2)

  1. Add RightTriangle(a, b) to the shape hierarchy (area = a·b/2, perimeter = a + b + hypotenuse). For RightTriangle(3, 4), what are the area, perimeter and draw() outputs? What changes in the shape loop?
  2. Rewrite the instanceof chain loop (Dog → bark, Cat → scratch, otherwise → "No special behavior") without any instanceof.
  3. Given overloads print(Animal) and print(Dog), does Object o = new Dog(); print(o); compile?
Answers / hints
  1. Right triangle area: 6.0, Right triangle perimeter: 12.0, Right triangle drawn. (draw() not overridden). The loop never changes; only a new object is added to the array.
  2. Add void specialBehavior() ("No special behavior") to Animal; Dog and Cat override it. The loop: x.specialBehavior(); → the same three lines.
  3. No: the declared type is Object; neither version accepts an Object (no suitable method found for print(Object)). print((Dog) o) compiles.

Summary

References

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

The End

Chapter 4.4: Polymorphism
Previous: Chapter 4.3: Inheritance · Next: Chapter 4.5: Abstract Classes and Interfaces
1 / 1 Sercan KÜLCÜ. All rights reserved.