我有一些这样的场景:
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”对象数组时,编译器给了我受保护的访问错误:
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);
我不知道这两种方式有什么区别。