Chapter 4.4: Polymorphism
Multiple Choice · The Idea of Polymorphism
Question 1: Who Chooses?
Which statement is true about run-time polymorphism?
A: Overriding + dynamic binding is resolved at run time from the object’s actual type; it needs a class hierarchy. Overloading is the compiler’s choice at compile time, based on the declared types of the arguments (B and D describe that).
Multiple Choice · References and Type Compatibility
Question 2: Which Assignment Compiles?
Dog and Cat extend Animal. Which line compiles?
C: A superclass (here Object) reference can refer to a subclass object. A: not every animal is a dog (Animal cannot be converted to Dog). B: there is no assignment between sibling classes. D: even though the object is a dog, the compiler sees the declared type of a (Animal); an explicit cast is needed.
Spot the Bug · References and Type Compatibility
Question 3: Compiles or Runs?
side() is defined only in Square, and the abstract area() in Shape. For each line decide: compile error, run-time error, or fine.
Shape s = new Square(2); Square k1 = s; // 1 Square k2 = (Square) s; // 2 s.side(); // 3 Object o = k2; o.area(); // 4 double a = ((Shape) o).area(); System.out.println(a); // 5 Circle c = (Circle) s; // 6
Show answer
| # | Result | Why |
|---|---|---|
| 1 | Compile | Shape → Square needs an explicit cast |
| 2 | Fine | The object really is a Square |
| 3 | Compile | Shape has no side() |
| 4 | Compile | Object has no area() |
| 5 | Fine | prints 4.0 (dynamic binding) |
| 6 | Run | ClassCastException: a Square, not a Circle |
The compiler looks only at the reference type; the JVM checks the validity of the cast (6) by looking at the object.
Step-by-Step Trace · Type Conversion
Question 4: One Object, Four Views
Which casts succeed? Where does the program stop, and what has it printed by then?
A single Dog object; o, of type Object, refers to it (upcast, automatic).
(Animal) o is a downcast: the JVM checks that the object is an Animal. No new object is created.
Even though the reference type is Animal, the object is a Dog: Dog.makeSound() runs.
(Dog) d succeeds; bark() can now be called, because the reference type is Dog.
Three references, one object: o == k → true. A cast changes the view, not the object.
The compiler allows it (an Animal might well be a Cat), but the JVM looks at the object: ClassCastException. end is never printed.
// Animal, Dog (adds bark()) and Cat // override makeSound(). Object o = new Dog(); Animal h = (Animal) o; h.makeSound(); Dog k = (Dog) h; k.bark(); System.out.println(o == k); Cat c = (Cat) h; System.out.println("end");
Multiple Choice · Type Conversion
Question 5: It Compiles, But…
Which statement is true for the line Dog d = (Dog) new Animal();?
B: An explicit cast from a supertype to a subtype is accepted by the compiler. But the object is a plain Animal; at the moment of the cast the JVM checks the object’s actual class and says Animal cannot be cast to Dog. A superclass object can never be assigned to a subclass reference.
Multiple Choice · Type Conversion
Question 6: Where Are the Parentheses?
After Animal a2 = new Dog();, the statement (Dog) a2.bark(); is written. What happens?
D: The . operator binds before the cast: the expression reads like (Dog) (a2.bark()) and gives error: not a statement; even if that were fixed, Animal has no bark(). The correct form is ((Dog) a2).bark();.
Step-by-Step Trace · Dynamic Binding
Question 7: Which Class Holds the Method?
For each of the four calls, in which class does the lookup end? What does the program print?
k refers to a Cat object. The arrows point from subclass to superclass (extends); Object is at the very top.
The lookup starts in the object’s actual class Cat: eat() exists there, so the overridden version runs.
introduce() is not in Cat; the lookup moves up one level. Animal’s version is found and the search stops; Creature’s is never looked at.
breathe() is found two classes up, in Creature: inheritance passes along the whole chain.
toString() is in none of our classes: Object’s version returns “class name@hex code”, so the result is true.
// p(s): System.out.println(s) class Creature { void breathe() { p("The creature breathes"); } void introduce() { p("I am a creature"); } } class Animal extends Creature { @Override void introduce() { p("I am an animal"); } void eat() { p("The animal eats"); } } class Cat extends Animal { @Override void eat() { p("The cat eats fish"); } } // in main: Cat k = new Cat(); k.eat(); k.introduce(); k.breathe(); System.out.println(k.toString().startsWith("Cat@"));
Multiple Choice · Dynamic Binding
Question 8: What Is Not Dynamically Bound?
What does the program print?
class Parent { String name = "parent"; static String s() { return "Parent.s"; } String m() { return "Parent.m"; } } class Child extends Parent { String name = "child"; static String s() { return "Child.s"; } @Override String m() { return "Child.m"; } } // in main: Parent u = new Child(); System.out.println(u.name + " " + u.s() + " " + u.m());
C: Only instance methods are chosen (dynamically) by the type of the object: u.m() → Child.m. Field access and a static method call are bound at compile time by the reference’s declared type (Parent): u.name → parent, u.s() → Parent.s. A same-named field or static method in the subclass only hides, it does not override.
Step-by-Step Trace · Dynamic Binding
Question 9: show() Called from a Constructor
The constructor of Parent calls show(), which Child overrides. What does the program print? Why does x appear with two different values?
The object is allocated and x is the default 0. The first job of Child() is the implicit super(): the initializer x = 5 has not run yet.
The body of Parent() runs: Parent.
show() = this.show(); the object is a Child, so dynamic binding selects Child.show(). x is still 0: Child.show x=0.
After super() returns, Child’s field initializers run: x = 5.
Only now the body of Child(): Child 5. Lesson: calling an overridable method from a constructor exposes a half-built object.
class Parent { Parent() { System.out.println("Parent"); show(); } void show() { System.out.println("Parent.show"); } } class Child extends Parent { int x = 5; Child() { System.out.println("Child " + x); } @Override void show() { System.out.println("Child.show x=" + x); } } // in main: new Child();
Output Question · Dynamic Binding
Question 10: P, Q, R
Q overrides only b(), and R overrides only a(). What does the program print on its three lines?
class P { void a() { System.out.print("P.a "); b(); } void b() { System.out.print("P.b "); } } class Q extends P { @Override void b() { System.out.print("Q.b "); } } class R extends Q { @Override void a() { System.out.print("R.a "); super.a(); } } // in main: P x = new R(); x.a(); System.out.println(); new Q().a(); System.out.println(); new P().a(); System.out.println();
Show answer
R.a P.a Q.b P.a Q.b P.a P.b
x.a(): the object is anR→R.a;super.a()runsP.a(Qhas noa).- The
b()insideP.aisthis.b();thisis anR, and the nearestb()is inQ:Q.b. new Q().a():acomes fromP,bisQ’s. On a plainPobject both areP’s.
Multiple Choice · Dynamic Binding
Question 11: Which One Is Dynamic?
For Animal a = new Dog();, in which of the following is the code that runs chosen by the object’s type?
A: Overridden instance methods are bound dynamically. Fields and static methods are chosen by the reference type; a final method cannot have another version in a subclass, so the only candidate is Animal’s anyway.
Multiple Choice · Overloading
Question 12: Overloadingde Bildirilen Tip
display(Animal) and display(Dog) are overloaded. What does Animal a = new Dog(); display(a); print?
D: The compiler chooses among the overloaded versions by the declared type of the argument: a has type Animal. The fact that the object is a Dog does not change this choice. Had display((Dog) a) been written, display(Dog) would be chosen.
Output Question · Overloading
Question 13: Which show?
There are three overloaded show methods. What do the five calls in main print?
static void show(int x) { System.out.println("int " + x); } static void show(double x) { System.out.println("double " + x); } static void show(Object o) { System.out.println("Object " + o); } // in main: show('B'); show(7L); show(2.5f); show("7"); show(Integer.valueOf(7));
Show answer
int 66 double 7.0 double 2.5 Object 7 Object 7
'B'(char) widens toint: its code, 66.longandfloatcannot narrow toint; they widen todouble.Stringfits onlyObject.Integeris an object: since it fitsObjectwithout unboxing, that is chosen first (unboxing is tried only in a later phase).- Two methods that differ only in return type cannot be written at all:
method ... is already defined.
Step-by-Step Trace · Overloading
Question 14: Compiler First, Then the JVM
For each of the five calls, which signature does the compiler choose, and which version does the JVM run?
A single Child object; u sees it as a Parent, a as a Child. o refers to a boxed Integer.
The compiler sees only Parent’s methods; the declared type of o is Object → f(Object). JVM: the object is a Child, the overridden version.
Both versions fit; the most specific, f(String), is chosen. Since Child does not override it, Parent’s runs.
Parent has no f(Integer): 5 is boxed and fits Object. The chosen signature is f(Object); at run time, Child’s version.
Same object, but the reference type is Child: f(Integer) is now visible and more specific than f(Object).
Even though the object o refers to is an Integer, the declared type is Object: only f(Object) fits.
// p(s): System.out.println(s) class Parent { void f(Object o) { p("Parent.f(Object)"); } void f(String s) { p("Parent.f(String)"); } } class Child extends Parent { @Override void f(Object o) { p("Child.f(Object)"); } void f(Integer i) { p("Child.f(Integer)"); } } // in main: Parent u = new Child(); Child a = (Child) u; Object o = 5; u.f(o); u.f("x"); u.f(5); a.f(5); a.f(o);
Output Question · Inheritance and Polymorphism
Question 15: An Array of Shapes
Shape is abstract; draw() prints the class name, and only Rectangle overrides it. What does the program print?
abstract class Shape { abstract double area(); void draw() { String name = getClass().getSimpleName(); System.out.println(name + " drawn"); } } // area(): Square(k) → k*k, Rectangle(a, b) → a*b, // RightTriangle(a, b) → a*b/2 // Rectangle's draw() prints: // "Rectangle: " + a + "x" + b static double totalArea(Shape[] array) { double total = 0; for (Shape s : array) { total += s.area(); s.draw(); } return total; } // in main: Shape[] d = { new Square(3), new Rectangle(2, 5), new RightTriangle(3, 4) }; System.out.println(totalArea(d));
Show answer
Square drawn Rectangle: 2.0x5.0 RightTriangle drawn 25.0
- In each round
s.area()runs the object’s own formula: 9.0 + 10.0 + 6.0 = 25.0. SquareandRightTriangledid not overridedraw():Shape’s version runs;getClass()still returns the object’s actual class.- Adding a new shape does not change
totalAreaat all.
Output Question · Inheritance and Polymorphism
Question 16: The equals(Person) Trap
The class Person has an equals(Person) method. What does the program print?
class Person { String name; Person(String name) { this.name = name; } public boolean equals(Person k) { return name.equals(k.name); } } // in main: Person a = new Person("Ali"); Person b = new Person("Ali"); Object o = b; System.out.println(a.equals(b)); System.out.println(a.equals(o)); System.out.println(o.equals(a));
Show answer
true false false
equals(Person k)does not overrideequals(Object)ofObject, it overloads it.a.equals(b): the argument is aPerson→ the new method →true.a.equals(o): the argument’s declared type isObject→Object.equalsis chosen; reference comparison →false.o.equals(a): on typeObjectonlyequals(Object)is visible; it is not overridden, so againfalse. Had@Overridebeen written, the error would have been caught at compile time.
Coding Question · Inheritance and Polymorphism
Question 17: Payment Types
The class Payment is ready (protected double amount, a constructor Payment(double amount), and payable() = amount). Write CreditCard, which extends it (2% commission: amount × 1.02), and Installment, which extends CreditCard (in addition to the card’s amount, 5 TL per installment). What is the total payable for the array { new Payment(100), new CreditCard(200), new Installment(300, 3) }?
Show answer
class CreditCard extends Payment {
CreditCard(double amount) { super(amount); }
@Override double payable() { return amount * 1.02; }
}
class Installment extends CreditCard {
int installments;
Installment(double amount, int installments) {
super(amount); this.installments = installments;
}
@Override double payable() {
return super.payable() + 5 * installments;
}
}
// total += o.payable(); (Payment o : list)100.0 + 204.0 + (306.0 + 15) = 625.0. The loop knows only the type Payment; super.payable() reuses the commission rule without rewriting it.
Multiple Choice · Inheritance and Polymorphism
Question 18: Why Polymorphism?
What is the real benefit of calling s.computeArea() instead of computing the total area with an instanceof chain (if (s instanceof Square) … else if …)?
B: The call is written once with the superclass type; the object decides which version runs. If a new type is forgotten in the chain, a silently wrong result (e.g. 0) appears. Speed is not the main goal (A); compiler checking continues (C); every concrete subclass must still implement the abstract method (D).