101k views
0 votes
Analyze the following code:

public class A extends B {
}

class B {
public B(String s) {
}
}
A. The program has a compile error because A does not have a default constructor.
B. The program has a compile error because the default constructor of A invokes the default constructor of B, but B does not have a default constructor.
C. The program would compile fine if you add the following constructor into A: A(String s) { }
D. The program would compile fine if you add the following constructor into A: A(String s) { super(s); }

1 Answer

1 vote

Final answer:

Class A must define a constructor that calls superclass B's constructor since B does not have a default constructor. The correct construct to add to class A to compile successfully is A(String s) { super(s); },

Step-by-step explanation:

The question deals with the rules of constructors in Java inheritance. When you create a subclass that extends a superclass without a default constructor (a constructor without parameters), you must explicitly call a superclass constructor that matches the parameters you define in the subclass's constructor. In this case, class B has a constructor that takes a String as a parameter and class A extends class B, but does not define any constructor.

Hence, the default constructor of class A attempts to invoke the default constructor of class B, which does not exist. This leads to a compilation error.

To resolve this issue and successfully compile the program, you would need to add a constructor in class A that explicitly calls the superclass's constructor with the appropriate parameter. The correct code snippet to add to class A would be:

A(String s) { super(s); }

By doing this, class A will have a constructor that correctly matches and calls the existing constructor in class B.

User Igor Timoshenko
by
8.3k points