Chapter 4.4: Polymorphism
Introduction
Learning Outcomes
Define polymorphism and distinguish compile-time from run-time polymorphism.
Explain why a superclass reference can hold a subclass object, and why the reverse is a compile error.
Write upcasts and downcasts; prevent ClassCastException with instanceof.
Trace step by step how the method called is chosen by the object's actual class; show the method lookup in the hierarchy.
Compare overloading with overriding; know which one the compiler picks and which one the JVM picks.
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()printsWoof woof!for a dog andMeow!for a cat.- We write the code once, against the superclass; each object answers the call with its own version.
The Idea of Polymorphism
Two Kinds of Polymorphism
| Compile time (static) | Run time (dynamic) | |
|---|---|---|
| Mechanism | Overloading | Overriding + dynamic binding |
| Who chooses | The compiler (javac) | The JVM, while the program runs |
| What is checked? | Number and declared types of the arguments | The object's actual class |
| Needs inheritance? | No, works within one class | Yes, 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
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"); } }
DogoverridesmakeSound()andrun()and addsbark();Catoverrides onlymakeSound()and addsscratch().- 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());
new Dog() creates one object on the heap; the dog reference points to it.
No new object is created: animal is a second reference to the same object. A Dog is an Animal, so the assignment is legal.
Every class extends Object, so an Object reference can point to the same object too.
== compares references: both point to the same object, so true.
Still the same object: true. Three references, one object.
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 h = new Dog(); // declared type: Animal // actual type: Dog
| Question | Who 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.Type Conversion
Upcasting and Downcasting
| Upcasting | Downcasting | |
|---|---|---|
| Direction | Sub → super | Super → sub |
| Syntax | Automatic (implicit) | Explicit: (Dog) h |
| Safe? | Always | Depends on the object |
| Also called | Widening | Narrowing |
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(); // wrongerror: not a statement
String s = (Dog) h2.name();
// h2.name() first → not in Animalerror: 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
Animalmay well point to aDog. - The JVM checks the object's actual class at the cast: if it is a
Cator a plainAnimal, 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
Upcast: h1, of type Animal, points to a Dog object.
h2 points to a Cat. To the compiler both are just Animal.
The compiler allows the cast. At run time the JVM checks the object: it really is a Dog. k1 points to the same object.
Through a Dog reference, bark() can be called.
This line compiles too. But going up the chain from Cat, the JVM finds no Dog.
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:trueif the object is aTypeor a subclass of it.- Test first, then cast: no
ClassCastExceptioncan occur.null instanceof Typeis alwaysfalse.
Java 16+: pattern matching
if (x instanceof Dog kk) { kk.bark(); // cast is automatic }
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
All three elements are references of type Animal; the objects they point to are of different classes.
First iteration: x is a Cat. The Dog test is false.
The Cat test is true; since it was tested first, the cast (Cat) x is safe: Cat scratches.
Second iteration: a plain Animal. Not an instance of any subclass: both tests are false.
The else branch runs; no cast is attempted, so no risk.
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
Dogis anAnimal, so aDog[]also counts as anAnimal[]and the upcast compiles. - But the array object is really a
Dog[]. Storing aCatin it through theAnimal[]reference looks fine to the compiler; the JVM checks the element type on every store and throwsArrayStoreException. - Generic collections close this hole at compile time: a
List<Dog>is not aList<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
h's type (Animal): does it have run()? Yes → the call compiles. Otherwise, a compile error.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
The object is a Dog: lookups always start at the bottom, at the actual class.
Dog has run() → lookup ends, the Dog version runs.
Dog has no sleep() → go up one level: found in Animal.
toString() is found at the top, in Object: class name + @ + hex hash code (varies between runs).
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(); }
Animal array of 3: the elements are references, initially null.
Element 0 points to a Dog (upcast, automatic).
Element 1 points to a Cat.
Element 2 is a plain Animal object. The array now holds three different forms.
i = 0, 0 < 3 true → loop body.
Same line, different object: the JVM checks the object's class → Dog.makeSound().
i = 1, 1 < 3 true → loop body.
Same line, different object: the JVM checks the object's class → Cat.makeSound().
i = 2, 2 < 3 true → loop body.
Same line, different object: the JVM checks the object's class → Animal.makeSound().
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'srunslot → 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
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
The two objects in the array belong to different classes; each carries a link to its own class's table.
The bytecode says “Animal.run, slot 1”. The object is a Dog: slot 1 of its table holds Dog.run.
Same path, slot 0: Woof woof!
Same bytecode, different object. Cat does not override run, so slot 1 of its table points to Animal.run.
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
| Member | Chosen by |
|---|---|
| Instance method | Object type (dynamic) |
| Field | Reference type (static) |
static method | Reference type (static) |
private / final | Cannot 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
The subclass's kind does not override the superclass's, it hides it: the object has two separate fields.
Fields are not dynamically bound: h's declared type is Animal, so Animal.kind is read: animal.
static methods belong to the class; the compiler binds h.info() to Animal.info().
Instance methods are dynamically bound: Dog.introduce() runs, and inside it kind is Dog's field: I am a dog.
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 thedraw()call in the superclass constructor runsLabel.draw(). - But at that moment the subclass field initializers have not run yet:
textis stillnull. 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,finalorstaticmethods 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)
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
new allocates the object; text is null by default. The first thing Label() does is the implicit super() call.
Component()'s body prints the first line.
draw() = this.draw(). The object's class is Label, so the overridden version is chosen; but text is not assigned yet: Label: null.
After the superclass constructor returns, the subclass field initializer runs: text = "Hello". Too late: draw() was already called.
The Label() body runs; the object is now built.
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)
animalpoints to aDog, yetprint(animal)→print(Animal).- The compiler picks among overloads by the argument's declared type.
- A cast changes the declared type:
(Dog) animal→print(Dog).
| Overloading | Overriding | |
|---|---|---|
| Where? | Same class | Subclass |
| Signature | Different parameters | Same signature |
| Chosen at | The compiler | The JVM |
| Based on | Declared type | Actual 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:
Catfits bothAnimalandObject;Animalis more specific. nullfits every reference type.AnimalandStringare 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
Both variables have the same declared type (Animal); the objects differ: Dog and Cat.
animal points to a Dog, but the compiler knows only the declared type: print(Animal).
Inside the method, h.makeSound() is an overridden method: the JVM looks at the object: Woof woof!
other is also of type Animal: the same version is chosen.
Same line, different object: this time Cat.makeSound(), Meow!
The explicit cast makes the declared type Dog: this time the compiler picks print(Dog).
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
Only exact matches, primitive widening (int → long) and reference widening (String → Object) are tried.
If phase 1 finds no candidate, boxing and unboxing are tried too: double → Double → Object.
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)andf(Integer), the callf(5)picksf(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
5 is an int. In phase 1 only long fits, by widening; Integer and Object need boxing and are not tried in this phase.
byte also widens to long. Even boxed it would be a Byte, not an Integer.
The argument is already an Integer: phase 1 has two candidates. Integer is more specific than Object, so it wins.
A String fits only Object.
A double cannot be narrowed to long; phase 1 has no candidate. In phase 2 it is boxed to Double, which fits Object.
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
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.
Inheritance and Polymorphism
Example: Shape Hierarchy
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(); }
The array is of type Shape; its elements point to objects of three different subclasses.
shape.area() → Square.area() runs.
draw() overridden → Square.draw() runs.
shape.area() → Rectangle.area() runs.
Rectangle does not override draw() → lookup goes up, Shape.draw() runs.
shape.area() → Circle.area() runs.
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 Shapeclass; this code never changes. - { Square(5), Rectangle(4, 6), RightTriangle(3, 4) } → 55.0
- Shorter code, and no
ClassCastExceptionrisk.
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.
examineneeds no change for a newBirdclass. - Return type of superclass type: the method hides which subclass it creates. The caller relies only on the
Animalcontract; ifadoptstarts 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
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
AntiTankandTank.
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
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
equalsruns:p.equals(k)runsPoint's,k.equals(p)runsColoredPoint's. - The results differ: symmetry is broken. A
HashSetorcontainsmay answer differently depending on the order of elements. - Fixes: compare
getClass()in both classes; or use composition instead of inheritance (ColoredPointholds aPointfield).
Summary
Summary
| Concept | Rule | Example |
|---|---|---|
| The reference rule | A superclass reference can point to a subclass object; the reverse won't compile | Animal h = new Dog(); |
| is-a | A subclass object is a superclass object; not the reverse | h instanceof Animal → true |
| Upcasting | Automatic and always safe | Object o = dog; |
| Downcasting | Explicit; if the object doesn't fit, ClassCastException | Dog k = (Dog) h; |
| Access | The reference type decides which methods can be called | h.bark() → compile error |
| Dynamic binding | The object type decides which version runs; lookup goes bottom-up | h.run() → Dog version |
| Static binding | Fields, static/private/final methods and overload selection | h.kind → "animal" |
| Benefit | Code written once against the superclass works unchanged with new subclasses | totalArea(shapes) |
Summary
Related Pages
Defining interfaces and implements, polymorphism through interface references, multiple interfaces, default/static/private interface methods, generics.
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
| Code | Compiler message | Cause / fix |
|---|---|---|
Dog k = new Animal(); | incompatible types: Animal cannot be converted to Dog | Not every animal is a dog; the reverse assignment is illegal. |
Dog k = animal; | incompatible types: Animal cannot be converted to Dog | Even if the object is a dog, an explicit cast is needed: (Dog) animal. |
animal.bark(); | cannot find symbol … variable animal of type Animal | The reference type has no such method; downcast first. |
(Dog) h.bark(); | not a statement | Missing parentheses: ((Dog) h).bark(); |
(Cat) dog | incompatible types: Dog cannot be converted to Cat | There is no cast between sibling classes. |
@Override void makesound() | method does not override or implement a method from a supertype | Name misspelled (case matters). |
void makeSound() (super: public) | attempting to assign weaker access privileges; was public | An overriding method cannot reduce access. |
Summary
Common Mistakes (2): Run Time and Logic
Writing (Dog) h and forgetting that h may point to a Cat → ClassCastException. Test with instanceof first.
(Animal) dog does not turn the dog into an animal; makeSound() still prints "Woof woof!".
h.kind is read by the reference type ("animal"). Fix: make fields private and override a getter instead.
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 everywhereThey break as subclasses are added. Move the behavior into an overridden method.
Summary
Common Mistakes (3)
The subclass method runs on an object whose fields are not yet set: null output or NullPointerException.
Animal[] d = new Dog[2]; d[1] = new Cat(); compiles, but at run time: ArrayStoreException: Cat.
show(null), with two unrelated overloads: reference to show is ambiguous. Resolve it with an explicit cast.
With f(long) and f(Integer), f(5) → f(long): widening is in phase 1.
p.equals(k) true, k.equals(p) false: symmetry breaks, collections behave inconsistently.
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():Bhas nocall→A.call()runs.- The inner
print()is reallythis.print();thisis aBobject → dynamic binding picksB.print(). new A().call(): the object is anA→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
| # | Result | Reason |
|---|---|---|
| 1 | Compile | Animal → Cat needs an explicit cast |
| 2 | Fine | The object really is a Cat |
| 3 | Run time | ClassCastException: Cat → Dog fails |
| 4 | Compile | Animal has no scratch() |
| 5 | Fine | "Cat scratches" |
| 6 | Compile | Object has no makeSound() |
| 7 | Fine | "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)
- The compiler picks the version:
o's declared type isObject→f(Object). At run time the object is aChild→ overridden version: Child.f(Object). - Argument
String→ best versionf(String).Childdoesn'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); } }
new Child();and thennew Child().show();print what?- Given
f(long),f(Integer),f(Object)andf(int...), which versions doshort s = 3; f(s);,f('A');andf(Long.valueOf(4));choose? Object[] d = new String[1]; d[0] = 1;: compiles? runs?
Show answers
- no arr, then no arr and length 3: during every
new Child(),Parent()callsChild.show()beforearris assigned; after construction arr is ready. - f(long), f(long), f(Object):
shortandcharwiden tolong. ForLong,f(long)needs unboxing; the only phase-1 candidate isObject. - Compiles, but at run time
ArrayStoreException: java.lang.Integer: 1 is boxed toIntegerand cannot be stored in an array that is really aString[].
Summary
Exercises (1)
- Write
Employee(salary()= base salary),Manager(base × 1.5) andIntern(fixed 5000). ForEmployee[]= { Ayşe 20000, Manager Mehmet 30000, Intern Can }, what is the total salary? X:name()→ "X",print()→println(name()).Y extends X:name()→ "Y".Z extends Y:print()→println("Z:" + name()). What is printed ifprint()is called on each of { new X(), new Y(), new Z() }?Object o = new Dog();followed byo.makeSound();: why doesn't it compile? How do you fix it, and what does it print then?
Answers / hints
Manager.salary()is overridden withreturn baseSalary * 1.5;; in the looptotal += c.salary();→ 20000 + 45000 + 5000 = 70000.0.- X, Y, Z:Y. In Y,
print()comes from X but thename()inside it is Y's; in Z,name()comes from Y. Objecthas nomakeSound()(cannot find symbol).((Animal) o).makeSound();→ Woof woof!
Summary
Exercises (2)
- Add
RightTriangle(a, b)to the shape hierarchy (area = a·b/2, perimeter = a + b + hypotenuse). ForRightTriangle(3, 4), what are the area, perimeter anddraw()outputs? What changes in the shape loop? - Rewrite the
instanceofchain loop (Dog → bark, Cat → scratch, otherwise → "No special behavior") without anyinstanceof. - Given overloads
print(Animal)andprint(Dog), doesObject o = new Dog(); print(o);compile?
Answers / hints
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.- Add
void specialBehavior()("No special behavior") toAnimal;DogandCatoverride it. The loop:x.specialBehavior();→ the same three lines. - No: the declared type is
Object; neither version accepts anObject(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.