官方介紹
可能大家都知道,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方法。
- 不在父類和資類所在的包中訪問,則沒有相應的權限