Differences between the four access modifiers in java and detailed explanation of the entire process
Client programmers: class consumers who use data types in their applications. Their goal is to collect various classes for fast application development.
Class Creator: A programmer who creates a new data type. The goal is to build a class.
Why access control exists: a. Allow client programmers to not touch what they should not; B. Allow library designers to change the internal working mode of the class without worrying about affecting client programmers
Four keywords of java: public, protected, default, and private (they decide who can use the things that follow them)
Applicability <the smaller the access permission range, the higher the Security>
Access permission package subclass other packages
Public writable zookeeper (available to anyone)
Protect allow privileges × (inherited classes can access and have the same permissions as private)
Default permission limit (package access permission, that is, the entire package can be accessed)
Private element ××× (no one except the type creator and the internal method of the type can access the element)
The following code is used to explain (four classes are created: Person Student Teacher Parents and one test class)
Package com. zq. demo. test1;
/**
* Class
* @ Author Administrator
*/
Public class Person {
Public String uname = "Wang Wu ";
Public void introduceMyself (){
System. out. println (uname );
}
}
Package com. zq. demo. test1;
// The same package
Public class Student {
Person p = new Person ();
Public void test (){
System. out. println (p. uname );
}
}
Package com. zq. demo. test1;
// Subclass
Public class Teacher extends Person {
Public int age;
Person p = new Person ();
Public void test1 (){
System. out. println (p. uname );
}
}
Package com. zq. demo. test2;
// Different packages
Import com. zq. demo. test1.Person;
Public class Parents {
Public String uname = "haha ";
Person p = new Person ();
Public void test2 (){
System. out. println (p. uname );
}
}
The test results show that public can access
Test protected using the same four classes
After changing The uanme in Person to protected, The Parents class reports The error The field Person. uname is not visible (meaning cross-packet is not allowed)
The other three are unaffected.
The access is not affected except for cross-package.
Private
Only this class can be accessed, but with the help of the uname set and get methods in the Person class
Default
Test results show that only access in this package is allowed. access in other packages is not allowed even if it is an inheritance relationship.