Bird
0
0

Given the code below, what will be the output?

medium📝 Predict Output Q5 of 15
Java - Packages and Access Control
Given the code below, what will be the output?
package pkg1;
public class Parent {
    protected int value = 5;
}

package pkg1;
public class Other {
    public static void main(String[] args) {
        Parent p = new Parent();
        System.out.println(p.value);
    }
}
A5
BCompilation error: value not accessible
C0
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Check package and access modifier

    Both classes are in the same package, so protected members are accessible.
  2. Step 2: Analyze output statement

    Accessing p.value prints 5 without error.
  3. Final Answer:

    5 -> Option A
  4. Quick Check:

    Protected accessible within same package [OK]
Quick Trick: Protected members accessible to all classes in same package [OK]
Common Mistakes:
  • Thinking protected restricts access to subclasses only
  • Expecting access error in same package
  • Confusing protected with private

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes