Hiprup

What are access modifiers in Java?

Java has four access modifiers that control visibility of classes, methods, and fields.

  • public — visible everywhere; the most permissive.

  • protected — visible within the same package and to subclasses (even in other packages).

  • default (package-private) — no keyword; visible only within the same package.

  • private — visible only within the declaring class; the most restrictive.

  • Best practice — default to private for fields and use the narrowest scope that works (encapsulation).

Know the exact scope of each modifier, especially the subtle difference between default (same package) and protected (same package + subclasses in other packages). The one-public-class-per-file rule is a practical detail.