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. }
  1. Change line 2 to: public int a;

  2. Change line 2 to :protected int a;

  3. Change line 13 to :public Sub() { this(5); }

  4. Change line 13 to :public Sub() { super(5); }


Correct Option: C,D
Explanation:

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

Find more quizzes: