Java · Question 15 · Hard

What will be the output of the following Java program?

class A {
    A() { System.out.print("A"); }
}

class B extends A {
    { System.out.print("b"); }
    B() { System.out.print("B"); }
}

class C extends B {
    C() {
        super();
        System.out.print("C");
    }
}

public class Main {
    public static void main(String[] args) {
        new C();
    }
}
  1. AbBc
  2. AbBC
  3. ABbC
  4. bABC
Answer and explanation

Answer: B. AbBC

Explanation: Creating C first runs A's constructor (prints A). Then B is initialised: its instance initialiser block runs before B's constructor body, printing b and then B. Finally C's constructor body prints C.

Previous: What will be the output of the following Java program? · Next: Which of the following is NOT a primitive data type in Java?

Practise java

Try a fresh set of java questions with an explanation after every answer, free and without signing up: Java practice. Or sit a full placement mock test.

More java questions

More technical & programming practice

Python · Data Structures · Algorithms · Object-Oriented Programming · DBMS · SQL · Operating Systems · Computer Networks

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge