java - 使用 Java 多态性限制对方法调用的访问

标签 java inheritance polymorphism protected

我有这样的场景:

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/

相关文章:

java - 继承 getter 和 toString() - java

oop - 继承基础知识

java - 具有继承性的实体的 JPA native 查询

C++ 零规则 : polymorphic deletion and unique_ptr behavior

php - OpenAPI PHP 客户端给出 Fatal Error with anyOf

java - 如何在 ActionListener 进行时更新 swing UI

java - Android 数据库到数组

java - Google Guava 从起始目录开始迭代所有文件

haskell - 哪些类型的问题可以帮助 "higher-kinded polymorphism"更好地解决?

java - 如何在 outlook 中选择一封电子邮件来断言内容