nerdexam
Oracle

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…

Working with Methods and Encapsulation

Question

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) { Acc obj = new Test(); } } Which statement is true?

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)
  • A
    12% (3)
  • B
    80% (20)
  • C
    4% (1)
  • D
    4% (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 (p and s): p has package-private (default) access - it's only visible within p1, and Test lives in p2.
  • C (r and s): r is protected, 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, and s): Combines both failures above - p is package-private and r hits 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

#Access Modifiers#Encapsulation#Package-private#Inheritance

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice