Bird
0
0

Consider the following code in two packages:

medium📝 Predict Output Q13 of 15
Java - Packages and Access Control
Consider the following code in two packages:
package pkg1;
public class Parent {
    protected int value = 10;
}

package pkg2;
import pkg1.Parent;
public class Child extends Parent {
    public int getValue() {
        return value;
    }
}

public class Test {
    public static void main(String[] args) {
        Child c = new Child();
        System.out.println(c.getValue());
    }
}

What is the output when running Test.main?
A0
B10
CCompilation error due to access
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Check access of protected member in subclass outside package

    The value field is protected in Parent. The Child class extends Parent and accesses value in getValue(). This is allowed because protected permits subclass access even outside the package.
  2. Step 2: Trace the output of getValue()

    The method returns value which is initialized to 10. So, printing c.getValue() outputs 10.
  3. Final Answer:

    10 -> Option B
  4. Quick Check:

    Protected allows subclass access outside package [OK]
Quick Trick: Protected allows subclass access outside package [OK]
Common Mistakes:
  • Thinking protected blocks subclass outside package
  • Expecting compilation error
  • Confusing default access with protected

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes