Card 09/ 10

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.

java
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
Each hierarchy, its output and the rule that produced it
HierarchyPrintsWhy
new B()ABConstructors complete from the top down, so the parent prints first
C ref = new D(); ref.go();Dgo() is overridden, and overriding is decided by the object's runtime type
E other = new F(); other.go();Ego(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.