Constructor Chain
Completed
Create A, B extends A and C extends B, each printing A(), B(), C() in its constructor. Read a letter and create that object, printing the constructors in the order they run, then done.
Input
One letter: A, B or C.
Output
The constructor messages, then done.
Example
Input
C
Output
A() B() C() done
Editor
Java
Hints
Every constructor first calls its parent's constructor (implicitly super()).
Solution explanation
Objects are built from the top of the hierarchy down, so parents are ready before children.
Show solution
import java.util.Scanner;
class A {
A() {
System.out.println("A()");
}
}
class B extends A {
B() {
System.out.println("B()");
}
}
class C extends B {
C() {
System.out.println("C()");
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String which = sc.next();
if (which.equals("A")) {
new A();
} else if (which.equals("B")) {
new B();
} else {
new C();
}
System.out.println("done");
}
}