of explains the difference between private protected public and default

  • 2020-05-16 06:55:24
  • OfStack

(1) for the public modifier, it has the maximum access rights and can access any class, interface, exception, etc. under CLASSPATH. It is often used in the external case, that is, the object or class external 1 interface form.

(2) for the protected modifier, its main purpose is to protect subclasses. What it means is that a subclass can use it to modify its members, and nothing else can, and it's a kind of inheritance passed to a subclass.

(3) for default, it also becomes friendly (friend) when it is a little bit, which is designed for the access of this package. Any class, interface, exception, etc. under this package can be accessed by each other, even if the parent class is not modified by protected.

(4) for private, its access is limited to the inner part of the class, which is a kind of encapsulation. For example, most of the member variables are decorated with private, and they do not want to be accessed by any other external class.

The following table shows the meaning and usage of the Java access control character

类内部 本包 子类 外部包
public
protected ×
default × ×
private × × ×

Note: the access control of Java stays at the compile level, meaning it does not leave any trace in the.class file and only checks the access control at compile time. In fact, by means of reflection, it is possible to access members of any class under any package; for example, it is also possible to access private members of a class.

The difference between:

(1) public: can be accessed by all other classes.

(2) private: can only be accessed and modified by itself.

(3) protected: itself, subclasses and classes in the same package can be accessed.

(4) default (default) : classes in the same package are accessible, and are declared without a modifier, as friendly.


Related articles: