Client Programmer: The class consumer who uses data types in his application, his goal is to collect various classes for rapid application development.
Class creators: Programmers who create new data types with the goal of building classes.
Reasons for access control: a. to keep client programmers from touching parts they shouldn't; b. to allow library designers to change the internal workings of classes without worrying about affecting client programmers
The four keywords of java: public, protected, default, private (they determine who can use what is defined next)
Scope of application <The smaller the scope of access rights, the higher the security>
Access Class Package Subclass Other Packages
public ∨ ∨ ∨ ∨ (available to anyone)
protect ∨ ∨ ∨ × (inherited classes can access and have the same permissions as private)
default ∨ ∨ × × (package access rights, that is, can be accessed in the entire package)
private ∨ × × × (elements that cannot be accessed by anyone other than the type creator and the type's internal methods)
Below, use the code to explain in detail (build four classes Person Student Teacher Parents and a test class)
package com.zq.demo.test1;
/**
* 类内
* @author Administrator
*/
public class Person {
public String uname = "王五";
public void introduceMyself(){
System.out.println(uname);
}
}
package com.zq.demo.test1;
//同一个包
public class Student {
Person p = new Person();
public void test(){
System.out.println(p.uname);
}
}
package com.zq.demo.test1;
//子类
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;
//不同包
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 result of the test class shows that public can be accessed in all of the above
Use the same four classes to test protected
After changing the uanme in Person to protected, the class Parents reports an error The field Person.uname is not visible (indicating that it cannot cross packages)
The other three have no effect
Description In addition to cross-package, others do not affect access
private
It can only be accessed in this class, but it can be accessed with the help of the set and get methods of uname in the Person class
default
The test result shows that it can only be accessed in this package, and cannot be accessed in other packages even if it is an inheritance relationship