Public private protected and default differences
In Java, class and member variables and member methods in a class are distinguished by access control specifier. Students who have just learned the Java language may not be very clear about the difference between public private protected and the default (generally called package access), especially the difference between protected and default. This is the story of this experience.
Method/Step
- 1
Private, as we all know, is only accessible in this class.
- 2
Public is just the opposite of private and can be accessed everywhere.
- 3
Protected is accessible within the package, and only its subclasses are accessible outside the package. , Package1 there is a class A in this package, which has a member variable A, which is decorated with the protected access control.
- 4
, another class in this package inherits from a, and it can access this member variable of a. If it is a normal class in this package (that is, it does not inherit from a), it is also possible to access the member variable of a, which you can test yourself.
- 5
, a normal class in another package accesses the member variable of a, which is not possible.
- 6
However, in a subclass of another package, that is, a class that inherits from a, accessing the member variable of a is possible.
- 7
Then the default (Package access permission). , or the member variable A of Class A in package1, this time nothing is added.
- 8
As with protected, this member variable of a can be accessed as long as it is a class under the same package, whether it is a subclass or any other ordinary class.
- 9
In another package class, if it is a normal class, like protected, you cannot access this member variable in Class A.
- 10
A class in another package, even a subclass, cannot access this member variable in Class A. This is not the same as protected.
- 11
To summarize, private is only accessible in this class, public is accessible, the default (package access rights) is only within the package to access, including the package of subclasses and ordinary classes, and protected is as long as the package can be accessed, including the package of subclasses and ordinary class, Other subclasses within the package can access it, but the normal class cannot access it. So protected and default (package access permissions) are very similar, in the same package, they are the same, and in another package, the default is inaccessible, and protected is only the subclass can access.
Public private protected and the default difference (go from Baidu)