Card 09/ 10
All 10 cards
ExerciseDifficulty: Advanced1 min
Three Hierarchies: Write Down What Prints
Three short hierarchies. For each, write down the complete output before opening the reveal — including the order of the lines.
class A { A() { System.out.print("A"); } }
class B extends A { B() { System.out.print("B"); } }
new B();
class C { void go() { System.out.print("C"); } }
class D extends C { void go() { System.out.print("D"); } }
C ref = new D();
ref.go();
class E { void go() { System.out.print("E"); } }
class F extends E { void go(int n) { System.out.print("F"); } }
E other = new F();
other.go();The three outputs, and the mechanism behind each
| Hierarchy | Prints | Why |
|---|---|---|
new B() | AB | Constructors complete from the top down, so the parent prints first |
C ref = new D(); ref.go(); | D | go() is overridden, and overriding is decided by the object's runtime type |
E other = new F(); other.go(); | E | go(int) has a different parameter list, so it overloads rather than overrides |
The third is the one that costs real time in real code. F looks as though it replaced go, and it added a second method that nothing is calling. An @Override annotation on it would have failed the build and said so.