我有这样的场景:
public class BaseClass {
protected void protectedMethod(OtherObject object) {
...
}
}
public class Child1 extends BaseClass {
@Override
protected void protectedMethod(OtherObject object) {
super.protectedMethod(object);
// Custom Child1 logic
...
}
}
public class Child2 extends BaseClass {
@Override
protected void protectedMethod(OtherObject object) {
super.protectedMethod(object);
// Custom Child2 logic
...
}
}
然后当我调用“protectedMethod”遍历“BaseClass”对象数组时,编译器给我提供了 protected 访问错误:
OtherObject other = new OtherObject();
BaseClass[] objects = {
new Child1(),
new Child2()
}
for (BaseClass object : objects) {
object.protectedMethod(other); //this line gives me protected access error
}
但如果我以不同的非多态方式做同样的事情,它工作正常。
OtherObject other = new OtherObject();
Child1 child1 = new Child1();
Child2 child2 = new Child2();
child1.protectedAccess(other);
child2.protectedAccess(other);
我不知道这两种方式有什么区别。
最佳答案
在 Java 中,“protected”访问限定符不仅允许子类访问,还允许同一包中的其他类访问。
如果您的最后一个代码片段与 Child1 和 Child2 在同一个包中,那么它将可以访问 Child1 和 Child2 中 protected 方法。
编辑:
您可以通过在自己的包中引入自己的基类来解决此问题并保持多态性。
public MyBaseClass extends BaseClass {
@Override
protected void protectedMethod(OtherObject object) {
super.protectedMethod(object);
}
}
public Child1 extends MyBaseClass { ... }
public Child2 extends MyBaseClass { ... }
然后使用您自己的基类类型的集合。
NyBaseClass[] objects = {
new Child1(),
new Child2()
}
for (MyBaseClass object : objects) {
object.protectedMethod(other);
}
关于java - 使用 Java 多态性限制对方法调用的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12710017/