官方介绍
可能大家都知道,JAVA中protected权限是本类、同包类、子类。
但是如果子类不在和父类不在同一个包中,那将会发生什么?
子类在其他包中访问
我们将父类和子类放在两个包中,如下所示:
父类:
package com.falcon.auth.father;
/**
* @Author falcon
* @Date 2020/3/19 19:23
**/
public class Father {
private String name ;
protected int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
子类:
package com.falcon.auth.son;
import com.falcon.auth.father.Father;
/**
* @Author falcon
* @Date 2020/3/19 19:23
**/
public class Son extends Father {
private String consumer ;
public static void main(String[] args) {
Son son = new Son();
son.setAge(10);
System.out.println(son.age == 0);
Father father = new Father();
father.setAge(30);
System.out.println(father.getAge());
}
}
可以发现:
- 若子类与父类不在同一包中,那么在子类中,子类实例可以访问其从父类继承而来的protected属性,而不能访问父类实例的protected方法。
不在父类和子类所在的包中访问
package com.falcon.auth;
import com.falcon.auth.father.Father;
import com.falcon.auth.son.Son;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AuthApplication {
public static void main(String[] args) {
SpringApplication.run(AuthApplication.class, args);
Son son = new Son();
son.setAge(10);
System.out.println(son.age); //编译报错
Father father = new Father();
father.setAge(30);
System.out.println(father.age);//编译报错
}
}
总结
- 父类的protected成员是包内可见的,并且对子类可见;
- 若子类与父类不在同一包中,那么在子类中,子类实例可以访问其从父类继承而来的protected方法,而不能访问父类实例的protected方法。
- 不在父类和资类所在的包中访问,则没有相应的权限