1Z0-803 · Question #131
Given: class X { private X() { } void one() { } } public class Y extends X { private Y() { } public static void main (String[] args) { new Y().one(); } } Which change will make this code compile?
The correct answer is B. Remove the private modifier from the X() constructor. The provided code fails to compile because class Y attempts to extend class X, but X's constructor is declared as private, preventing Y from implicitly calling super() during its own instantiation.
Question
Given:
class X { private X() { } void one() { } } public class Y extends X { private Y() { } public static void main (String[] args) { new Y().one(); } } Which change will make this code compile?
Options
- AAdd the public modifier to the declaration of class X
- BRemove the private modifier from the X() constructor
- CAdd the protected modifier to the declaration of the one() method
- DRemove the Y() constructor
- ERemove the private modifier from Y() constructor
How the community answered
(44 responses)- A11% (5)
- B75% (33)
- C7% (3)
- D2% (1)
- E5% (2)
Why each option
The provided code fails to compile because `class Y` attempts to extend `class X`, but `X`'s constructor is declared as private, preventing `Y` from implicitly calling `super()` during its own instantiation.
Adding the `public` modifier to the declaration of class `X` would not resolve the issue of `X`'s private constructor being inaccessible to its subclass `Y`.
Removing the `private` modifier from the `X()` constructor makes it accessible (default/package-private), allowing the `Y()` constructor to implicitly call `super()` and properly initialize its superclass `X`, thereby resolving the compilation error related to inheritance.
Adding the `protected` modifier to the declaration of the `one()` method would change its access level but does not address the fundamental problem of `Y` being unable to call an accessible constructor in its superclass `X`.
Removing the `Y()` constructor would result in a default public no-argument constructor being generated for `Y`, which would still implicitly attempt to call the inaccessible private `X()` constructor, leading to the same compilation error.
Removing the `private` modifier from `Y()` constructor would make it accessible from anywhere in the same package, but it does not resolve the issue of `Y`'s constructor needing to call an accessible `X()` constructor.
Concept tested: Java constructor access modifiers and inheritance
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Topics
Community Discussion
No community discussion yet for this question.