【问题标题】:Call method not defined in interface from implemented interface in Java从Java中实现的接口调用接口中未定义的方法
【发布时间】:2021-09-30 12:09:04
【问题描述】:

我在 Java 中有以下场景。假设我有一个接口和两个实现这个接口的类。如下:

public interface myInterface {

    public String printStuff();

}

public class A implements myInterface {

    @Override
    public String printStuff(){
        return "Stuff";
    }
}


public class B implements myInterface {

    @Override
    public String printStuff(){
        return "Stuff";
    }

    public String printOtherStuff(){
        return "Other Stuff";
    }
}

如果我定义如下,如何调用上面的printOtherStuff方法:

public static void main(String... args) {
 
     myInterface myinterface = new B();
     String str = myinterface.printOtherStuff(); // ? This does not work
}

上面的调用代码似乎不起作用。有什么想法吗?

【问题讨论】:

    标签: java interface


    【解决方案1】:
    myInterface myinterface = new B();
    

    myinterface 的引用类型是myInterface。这意味着您只能访问接口中定义的方法。您可以将其转换为类型 B 以进行方法调用。

    注意:从现在开始,我将使用正确的命名约定。

    示例

    MyInterface myInterface = new B();
    
    String str = ((B)myInterface).printOtherStuff();
    

    请注意

    如果你需要这样做,那么你需要看看你的类设计。以这种方式使用interface 的想法是从对象的具体实现的细节中抽象出来。如果您必须执行这样的显式转换,那么您可能需要考虑更改接口以适应必要的方法,或者更改您的类以便将方法移动到全局位置(如 util文件什么的)。

    补充阅读

    您应该阅读有关引用类型here 的内容,并且应该了解强制转换here。我的回答是对这两件事的理解结合起来。

    作为补充说明,请查看Java Naming Conventions。这是任何 Java 开发人员编写易于理解的代码的重要信息。

    【讨论】:

    • 谢谢!非常翔实的答案。额外感谢有关命名约定的提示。 :)
    【解决方案2】:

    这肯定行不通,因为您的引用类型为Interface MyInterface。在 方法绑定 编译器会尝试在您的 Interface MyInterface 中查找此方法,但该方法不可用。所以你需要像这样将它投射到你的班级。

        MyInterface myInterface = new B();
        B newB=(B) myInterface ;//casting to class
        newB.printOtherStuff();// would work fine
    

    【讨论】:

      猜你喜欢
      • 2014-03-13
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      相关资源
      最近更新 更多