(1) for the public modifier, it has the most access rights and can access any class, interface, exception, etc. under Classpath. It is often used for external situations, i.e. the form of an interface to an object or class outside.
(2) for the protected modifier, its main function is to protect the subclass. It means that the subclass can be decorated with its members, others cannot, it is equivalent to a subclass of the inheritance of something.
(3) For default, a bit of time also become friendly (friend), it is designed for this package access, any class, interface, exception, etc. under this package can be accessed, even if the parent class is not decorated with protected members can also.
(4) for private, its access is limited to the inside of the class, is a encapsulation embodiment, for example, most of the member variables are modifiers are private, they do not want to be accessed by any other external class.
The following table is the meaning and usage of the Java access control character
|
Inside the class |
This package |
Subclass |
External package |
public |
√ |
√ |
√ |
√ |
Protected |
√ |
√ |
√ |
x |
default |
√ |
√ |
x |
x |
private |
√ |
x |
x |
x |
Note: Java the access control is stuck at the compiler level, i.e. it will not be in the. Class leave any traces in the file and only check for access control at compile time. In fact, by means of reflection, it is possible to access any member of any class under any package, for example, to access a private member of a class.
Difference:
(1) Public: can be accessed by all other classes.
(2) Private: can only be accessed and modified by themselves.
(3) Protected: The class in itself, the subclass and the same package can be accessed.
(4) Default: Classes in the same package can be accessed and declared without modifiers, which are considered friendly.
Differences between public, protected, default, and Private in Java