Card 09/ 10
Practice: Predicting Output From Three Class Hierarchies
Constructor order, an override and an accidental overload: write down each output first.
Constructors complete from the most general class down, an override is chosen by the object's actual class, and a method with a different parameter list overrides nothing. Using those rules, write down the complete output of each of the three hierarchies below, including the order, before opening the answer.
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.
← → move through sections and cards