四种权限修饰符的测试
- A:案例演示
- 四种权限修饰符
B:结论
本类 同一个包下(子类和无关类) 不同包下(子类) 不同包下(无关类) private Y 默认 Y Y protected Y Y Y public Y Y Y Y
protected测试1:不同包下(无关类)是不能访问的。
package com.baidu;
public class Person {
private String name;
private int age;
public Person(){}
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void setNage(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
protected void print(){
System.out.println("print");
}
}
package com.heima;
import com.baidu.Person;
import java.util.Scanner;
class Demo01_Package {
public static void main(String[] args) {
Person p = new Person("张三",23);
System.out.println(p.getName() + "..." + p.getAge());
//在不同包下的无关类是不允许访问,因为是protected修饰的
p.print();
}
}
protected测试2:被protected修饰,在不同包下(子类)是可以访问的。
package com.baidu;
public class Person {
private String name;
private int age;
public Person(){}
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void setNage(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
protected void print(){
System.out.println("print");
}
}
package com.xxx;
import com.baidu.Person;
public class Student extends Person {
public Student(){}
public Student(String name,int age) {
super(name,age);
}
public void method() {
print();
}
}
package com.heima;
import com.xxx.Student;
import java.util.Scanner;
class Demo01_Package {
public static void main(String[] args) {
Student stu = new Student("李四",24);
System.out.println(stu.getName() + "..." + stu.getAge());
//被protected修饰,在不同包下的子类是允许访问
stu.method();
}
}