4 Types of Access Level

Private

Like you’d think, only the class in which it is declared can see it.

Package Private (default)

Can only be seen and used by the package in which it was declared.

This is the default in Java (which some see as a mistake).

Protected

Package Private, plus can be seen by subclasses.

Public

Everyone can see it.

Differences

Note: Java default access setting is ‘No modifier’, which is also called ‘Package Private‘.

Another note: by saying ‘subclass’, it means subclass declared in another package.

Example

Class structure:

For the methods of ‘Alpha’ class, the visibility is listed below.

For example, Gamma can only access public methods in Alpha.

Modifier Alpha Beta Alphasub Gamma
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

Additional question

Can we declare a top-level class as private?

Answer: No, Java does not allow top-level private class. Think about it, a top-level class as private would be useless because nothing could access it.

If you really want, you can use inner or nested classes. If you have a private inner or nested class, then access is restricted to the scope of that outer class.

link