Java access control: You want a class to access members of another class in the same package. What is the most restrictive access modifier that still allows access?

Difficulty: Easy

Correct Answer: default (package-private) access

Explanation:


Introduction / Context:
Access control in Java defines visibility across classes, packages, and inheritance hierarchies. This question asks for the most restrictive modifier that still permits access between two classes in the same package.



Given Data / Assumptions:

  • Two classes reside in the same package.
  • We want the smallest possible visibility that still allows access.
  • We compare public, private, protected, and default (package-private).


Concept / Approach:
Java provides four levels: private (class only), default/package-private (same package), protected (same package and subclasses in other packages), and public (everywhere). For same-package access, default/package-private is sufficient and more restrictive than protected or public.



Step-by-Step Solution:

private → only within the same class; too restrictive.default (no modifier) → accessible to any class in the same package; meets requirement.protected → also visible to subclasses in other packages; less restrictive than needed.public → visible everywhere; least restrictive.


Verification / Alternative check:
JLS confirms package-private visibility for members with no modifier and that it is the minimal scope for same-package access.



Why Other Options Are Wrong:
private blocks access; protected and public grant more access than required.



Common Pitfalls:
Confusing protected with package-private; protected includes package access but also adds cross-package subclass access.



Final Answer:
default (package-private) access

More Questions from Declarations and Access Control

Discussion & Comments

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