1Z0-808 · Question #54
package p1; public class Acc { int p; private int q; protected int r; public int s; } Test.java: package p2; import p1.Acc; public class Test extends Acc { public static void main(String[] args) {…
The correct answer is B. Only s is accessible by obj. Option B is correct because obj is declared with type Acc - and when accessing protected members from a different package, Java requires the reference type to be the subclass itself (Test) or a subtype of it, not the parent class (Acc). Since obj is typed as Acc, r is…
Question
Options
- ABoth p and s are accessible by obj.
- BOnly s is accessible by obj.
- CBoth r and s are accessible by obj.
- Dp, r, and s are accessible by obj.
How the community answered
(25 responses)- A12% (3)
- B80% (20)
- C4% (1)
- D4% (1)
Explanation
Option B is correct because obj is declared with type Acc - and when accessing protected members from a different package, Java requires the reference type to be the subclass itself (Test) or a subtype of it, not the parent class (Acc). Since obj is typed as Acc, r is off-limits despite Test being a subclass. Only public members are universally accessible, making s the sole accessible field.
Why the distractors fail:
- A (
pands):phas package-private (default) access - it's only visible withinp1, andTestlives inp2. - C (
rands):risprotected, which sounds subclass-friendly, but the JLS §6.6.2 rule blocks access when the qualifying reference type is the parent class from a different package. - D (
p,r, ands): Combines both failures above -pis package-private andrhits the same protected-access restriction as in C.
Memory tip: Think of it as "protected outside the package = you must use YOUR type, not your parent's." If the variable is declared as the superclass type, you lose protected access across packages.
Topics
Community Discussion
No community discussion yet for this question.