从 Java 中实现的接口调用未在接口中定义的方法 [英] Call method not defined in interface from implemented interface in Java

查看:44
本文介绍了从 Java 中实现的接口调用未在接口中定义的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following scenario in Java. Let's say I have an interface, and two classes that implement this interface. As follows:

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方法:

How do I call the printOtherStuff method above if I define it as follows:

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

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

The above calling code does not seem work. Any ideas?

推荐答案

myInterface myinterface = new B();

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

The reference type of myinterface is myInterface. That means you can only access the methods defined in the interface. You can cast it to type B in order to make the method call.

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

NOTE: From here on out I'll be using the proper naming conventions.

示例

MyInterface myInterface = new B();

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

简单说明一下

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

If you need to do this, then you need to have a look at your class design. The idea of using an interface in this way is to abstract away from the details of the object's concrete implementation. If you're having to perform an explicit cast like this, then you might want to look into either changing your interface to accommodate the necessary methods, or change your class so that the method is moved into a global location (like a util file or something).

额外阅读

您应该在此处阅读有关引用类型的信息,并且您应该看看在这里进行转换.我的回答是结合对这两件事的理解.

You should read about reference types here, and you should have a look at casting here. My answer is a combination of the understanding of both of these things.

作为补充说明,请查看 Java 命名约定.对于任何 Java 开发人员来说,这是制作易于理解的代码的重要信息.

As an added note, take a look at the Java Naming Conventions. This is a vital piece of information for any Java developer to make understandable code.

这篇关于从 Java 中实现的接口调用未在接口中定义的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆