Java access control across packages: You want subclasses in any package to have access to a superclass member. What is the most restrictive modifier that satisfies this?

Difficulty: Easy

Correct Answer: protected

Explanation:

Introduction / Context:Java's protected access is designed for inheritance, allowing subclass access across package boundaries while remaining more restrictive than public.

Given Data / Assumptions:

  • We need member visibility in subclasses regardless of package.
  • We prefer the most restrictive modifier that still works.

Concept / Approach:protected provides access to subclasses in any package (and also to all classes in the same package). default does not cross package boundaries. private is class-only. public is more open than required.

Step-by-Step Solution:

private → too restrictive.default → package-only; fails across packages.protected → allows subclass access in any package → correct.public → works but is less restrictive than necessary.

Verification / Alternative check:Create a subclass in a different package and verify access to a protected member compiles.

Why Other Options Are Wrong:transient is unrelated (serialization marker); others either overexpose or underexpose.

Common Pitfalls:Confusing protected with default.

Final Answer:protected

More Questions from Declarations and Access Control

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion