Which two, independently, will allow Sub to compile?
1. class Super {
2. private int a;
3. protected Super(int a) { this.a = a; }
4. }
...
11. class Sub extends Super {
12. public Sub(int a) { super(a); }
13. public Sub() { this.a = 5; }
14. }
-
Change line 2 to: public int a;
-
Change line 2 to :protected int a;
-
Change line 13 to :public Sub() { this(5); }
-
Change line 13 to :public Sub() { super(5); }
To solve this question, the user needs to know about access modifiers, constructors, and inheritance in Java.
Line 2 declares a private instance variable a in class Super, which cannot be accessed from the subclass Sub. Line 3 is a constructor that initializes the value of a. Line 11 declares a subclass Sub that inherits from Super.
Now, let's go through each option and explain why it is right or wrong:
A. Change line 2 to: public int a;
This option is incorrect because changing the access modifier of a to public would make it accessible from anywhere, including the subclass Sub. However, the a variable is still not visible in Sub, because it is declared in the superclass as private. Therefore, this option will not allow Sub to compile.
B. Change line 2 to: protected int a;
This option is correct because changing the access modifier of a to protected would make it accessible from the subclass Sub. Since a is now declared as protected in the superclass, it can be accessed from the subclass. Therefore, this option will allow Sub to compile.
C. Change line 13 to: public Sub() { this(5); }
This option is incorrect because changing the no-argument constructor to call another constructor with an argument using this would not compile since the superclass constructor is expecting an argument. Therefore, this option will not allow Sub to compile.
D. Change line 13 to: public Sub() { super(5); }
This option is correct because changing the no-argument constructor to call the superclass constructor that takes an argument will initialize the a variable in the superclass with the value of 5. Therefore, this option will allow Sub to compile.
Therefore, the correct answer is:
The Answer is: D
Super's only constructor is protected Super(int a) — there is no no-arg constructor, so Sub's no-arg constructor public Sub() must either explicitly call a Super constructor via super(a), or delegate to another constructor in Sub via this(...) that itself calls super. As written, public Sub() { this.a = 5; } fails to compile for two reasons: a is private in Super (not visible to Sub) and no super/this() call is made, so the implicit super() (no-arg) is inserted, which doesn't exist. Changing it to this(5) (delegates to Sub(int), which calls super(a)) or to super(5) (calls Super's constructor directly) both fix the missing-super-call problem. Changing field a's visibility doesn't fix the missing constructor call.