![]()
被 protected
修饰的成员对于本包和其子类可见:
- 基类的
protected
成员在包内可见
- 若继承了基类的子类与基类不在同一个包中,那么在子类中,子类实例可以访问其从基类继承而来的
protected
方法,不能访问基类中的 protected
方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
package com.example.demo.base; public class ProFather { protected void f() { System.out.println("protected father"); } }
package com.example.demo.base; public class ProSon1 extends ProFather { }
package com.example.demo.base2; public class ProSon2 extends ProFather { }
|
在基类所在的包中,基类,子类1和子类2都可以访问函数 f()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
package com.example.demo.base; public class BaseTest { public static void main(String[] args) { ProFather father = new ProFather(); father.f(); ProSon1 son1 = new ProSon1(); son1.f();
ProSon2 son2 = new ProSon2(); son2.f(); } }
|
在不同的包下,基类,子类1和子类2都不能访问函数 f()
,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
package com.example.demo.base2; public class Base2Test { public static void main(String[] args) { ProFather father = new ProFather(); father.f();
ProSon1 son1 = new ProSon1(); son1.f();
ProSon2 son2 = new ProSon2(); son2.f(); } }
|
在子类2中:
- 基类无法访问函数
f()
- 子类2可以访问函数
f()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
package com.example.demo.base2; public class ProSon2 extends ProFather { protected void f1() { super.f(); } public static void main(String[] args) { ProFather father = new ProFather(); father.f();
ProSon2 son2 = new ProSon2(); son2.f(); } }
|
如果子类2重写了父类的 f 方法,并用 protected
修饰,那么在子类2所在的包下可以访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
package com.example.demo.base2; public class ProSon2 extends ProFather { @Override protected void f() { super.f(); }
public static void main(String[] args) { ProSon2 son2 = new ProSon2(); son2.f(); } }
package com.example.demo.base2; public class Base2Test { public static void main(String[] args) { son2.f(); } }
|
参考资料
Java protected 关键字详解
本文首发于我的个人博客 https://chaohang.top
作者张小超
转载请注明出处
欢迎关注我的微信公众号 【超超不会飞】,获取第一时间的更新。
![]()