Access modifiers in java

There are four kinds of access modifiers in java, namely private, default, protected, and public. Their access permissions increase in turn. Private can only be called by this class, and default (default if not written) can be used with the same Called by all classes under a package, protected can be called by all classes under the same package, and can also be called by subclasses under different packages (that is, there must be an inheritance relationship), while public is public, All classes of all packages under the project can be called.

The code test is as follows:

The test results are as follows:

Except for the private class error, other access modifiers can be called in other classes in this package.

Tests in different packages:

Neither private nor default can be called in classes other than this package;

protected must be a subclass of the original class, that is, there is an inheritance relationship, so that it can be called in a class other than this package;

It can be called in the classes of all public packages (no need for inheritance).

 

I hope I can deepen my impression and better understand the knowledge about access modifiers.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325112722&siteId=291194637