【发布时间】:2012-10-03 13:53:48
【问题描述】:
我有这样的场景:
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);
我不知道这两种方式有什么区别。
【问题讨论】:
-
这两个子类是否与测试程序在同一个包中?
-
你从哪里调用方法??
-
不同之处在于,在第二个中您执行不同的方法(来自 Child1 和 Child2 类),但在第一个中您执行 BaseClass 的方法两次......也许您想制作 BaseClass(或protectedMethod) 抽象?
-
您在每种情况下都调用了不同的方法。有时您拨打
protectedMethod(),有时拨打protectedMethod(other),甚至拨打protectedAccess(other)。你的意思是这些都一样吗? -
@Shark 我无法修改基类,因为它来自外部依赖项,也许它的创建者出于某种原因这样做了,但我似乎无法找出那个原因。跨度>
标签: java inheritance polymorphism protected