Java supports four different kinds of access rights:
modifier |
Description |
Public |
Common, visible to all classes. |
Protected |
Protected, visible to classes and all subclasses within the same package. |
Private |
Private, visible within the same class. |
The default |
Visible within the same package. No modifiers are used by default. |
Public: Common
Classes, methods, construction methods, and interfaces that are declared public can be accessed by any other class.
If several publicly accessed public classes are distributed in unused packages, you need to import the package that contains the appropriate public class. Because of the inheritance of classes, all public methods and variables of a class can be inherited by their subclasses.
Protected: Protected
Variables, methods, and construction methods declared as protected can be accessed by any other class in the same package, or by subclasses in different packages.
The protected access modifier cannot decorate classes and interfaces , and methods and member variables can be declared as protected, but the member variables and member methods of an interface cannot be declared as protected.
subclasses can access the methods and variables declared by the protected modifier , which protects unrelated classes from using these methods and variables.
Private: Privately-owned
Private access modifiers are the most restrictive access level, so methods, variables, and construction methods that are declared private can only be accessed by the owning class, and classes and interfaces cannot be declared private.
Default: Do not use any keywords
Properties and methods declared with no modifiers are visible to classes within the same package. The variables in the interface are implicitly declared as public static final, and the methods in the interface are public by default.
Example
1 Public classdog{2 protected voidbark () {3SYSTEM.OUT.PRINTLN ("Bark! ");4 }5 }6 classTeddyextendsdog{7 voidbark () {8System.out.println ("haha");9 }Ten}
If the bark () method is declared private, a class other than dog will not be able to access the method. If you declare bark () as public, all classes have access to the method. If we only want the method to be visible to subclasses of its class, declare the method as protected.
access control and inheritance
Note the following methods inherit the rule:
Methods declared as public in the parent class must also be public in the subclass .
A method declared as protected in a parent class is either declared as protected in the subclass or declared as public. cannot be declared as private.
The method declared by the default modifier in the parent class, which can be declared as private in the subclass.
The method declared as privatE in the parent class is not sufficient to be inherited.
The difference between access control public/protected/private