四种权限修饰符的测试
- 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();
}
}

博客围绕四种权限修饰符展开测试。通过案例演示后得出结论,如protected修饰的内容,在不同包下的无关类不能访问,而在不同包下的子类可以访问。
847

被折叠的 条评论
为什么被折叠?



