There are altogether four access control permissions in Java, private, default, protected, and public
1. Private access Rights
Private access, which can be used in the definition of attributes, the declaration of methods, once the Private keyword declaration is used, can only be accessed in this class
2. Default access rights
If a property or method in a class does not use any of the access rights claims, it is the default access permission and the default access permission can be
The other classes in this package are accessed, but cannot be accessed by the classes of other packages.
3. Protected access Rights
Protected belongs to protected access rights. Members in a class can only be accessed by this package and the subclasses of different packages if protected access is used.
4. Public access Rights
Public is publicly accessible and can be accessed in all classes, regardless of whether they are in the same package, if the members in a class have access to the common user.
Use the table to summarize the above access control permissions.
| Range |
Private |
Default |
Protected |
Public |
| Same class |
√ |
√ |
√ |
√ |
| Classes in the same package |
|
√ |
√ |
√ |
| Subclasses in different packages |
|
|
√ |
√ |
| Classes in other packages |
|
|
|
√ |
The following describes the role of protected access control permissions
Define a Hellodemo class in the Com.home.a package that contains a protected access permission
package com.home.a;publicclass HelloDemo { protected"http://itmyhome.com"//只能被本包及不同包的子类访问}
The subclass in the com.home.b package accesses the URL property in this class
package com.home.b ; import com.home.a.hellodemo;class Subhellodemo extends hellodemo{//definition Hellodemo subclass public void print () {System.out.println ( "Access protected properties:" + URL); //can access protected permissions }} public class protectedtest { public static void main (string[] args) {Subhellodemo sub = new Subhellodemo (); Sub.print (); }}
Program Run Results
访问受保护属性: http://itmyhome.com
The protected attribute is accessed in subclasses of different packages in the above program, and if the class of the Hellodemo class is now accessed directly by the different package classes
Protected property, a compilation error occurs.
package com.home.b;import com.home.a.HelloDemo;publicclass ProtectedTest { publicstaticvoidmain(String[] args) { new HelloDemo(); // The field HelloDemo.url is not visible }}
Itmyhome
Java Access control permissions