私はこのようないくつかのシナリオを持っています:
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
...
}
}
次に、「BaseClass」オブジェクトの配列を反復処理する「protectedMethod」を呼び出すと、コンパイラは保護されたアクセスエラーを表示します。
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);
2つの方法の違いはわかりません。