40.6k views
3 votes
What is the output of running class C?

class A {
public A() {
System.out.println("The default constructor of A is invoked");
}
}

class B extends A {
public B() {
System.out.println("The default constructor of B is invoked");
}
}

public class C {
public static void main(String[] args) {
B b = new B();
}
}


A. Nothing displayed

B. "The default constructor of B is invoked"

C. "The default constructor of A is invoked" "The default constructor of B is invoked"

D. "The default constructor of B is invoked" "The default constructor of A is invoked"

E. "The default constructor of A is invoked"

User Tomaoq
by
7.8k points

1 Answer

2 votes

Final answer:

The output is the message from the superclass A's constructor followed by the message from the subclass B's constructor, indicating that the correct answer is option C.

Step-by-step explanation:

The output of running the class C would be:

The default constructor of A is invoked
The default constructor of B is invoked

When creating an instance of class B, which extends class A, Java will first invoke the constructor of the superclass A before executing the constructor of B. This is because B is a subclass of A, and in Java, the superclass constructor is called automatically if the subclass does not explicitly call a superclass constructor with super.

Therefore, since the default constructor of class A prints "The default constructor of A is invoked" and subsequently the default constructor of class B prints "The default constructor of B is invoked", the correct answer is C. "The default constructor of A is invoked" followed by "The default constructor of B is invoked".

User Vahe Muradyan
by
8.1k points