OA. free
Free
Warner Bros Data Structures & Algorithms Core Computer Science Medium

What is the output of executing the following Java program?

Warner Bros technical mcq question, verified with a worked answer. Free to practise - no sign-up.

What is the output of executing the following Java program?

class Person {
    public Person() {
        System.out.println("Person created");
    }
}

class Superhero extends Person {
    public Superhero() {
        System.out.println("Superhero created");
    }
}

class Batman extends Superhero {
    public Batman() {
        System.out.println("Batman created");
    }
}

class Main {
    public static void main(String[] args) {
        Batman myHero = new Batman();
    }
}
Choose one option.
Show answer & explanation
Answer: A. Person created Superhero created Batman created

In Java, constructors are called in order from the top of the inheritance hierarchy down to the most specific class. Each subclass constructor implicitly calls the superclass's no-argument constructor as its first action via an implicit super() call.

Step-by-step Derivation:
Step 1: The main method executes 'new Batman()', which invokes the Batman constructor.
Step 2: Before executing its own body, the Batman constructor implicitly calls super(), which is the Superhero constructor.
Step 3: Before executing its own body, the Superhero constructor implicitly calls super(), which is the Person constructor.
Step 4: The Person constructor (the root of the hierarchy) executes and prints 'Person created'.
Step 5: Control returns to the Superhero constructor, which prints 'Superhero created'.
Step 6: Control returns to the Batman constructor, which prints 'Batman created'.
Step 7: The final output sequence is: Person created, Superhero created, Batman created.