Video in progress

Compare the four access modifiers in Java by scope of visibility.

Inside the class / Inside the package / Child class (other package) / Everywhere — private: yes / no / no / no; (none): yes / yes / no / no; protected: yes / yes / yes / no; public: yes / yes / yes / yes

📖 Answer

Modifier Inside the class Inside the package Child class (other package) Everywhere
private yes no no no
(none) yes yes no no
protected yes yes yes no
public yes yes yes yes

A trap: thinking protected is only for child classes. In fact it is wider than package-private, since any class in the same package sees it too.

A practical tip is to start with the narrowest scope:

  • fields are almost always private;
  • leave helper classes used only inside the package without a modifier, so the external API stays small;
  • anything you make public is a promise others can depend on, and it is hard to change later.

A top-level class can only be public or package-private. In Java 9 modules, though, even a public class is invisible outside the module if its package isn't exportsed.