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

查看:236
本文介绍了调用方法未在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 interface myInterface {

    public String printStuff();

}

公共类A实现myInterface {

public class A implements myInterface {

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

}

公共类B实现myInterface {

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 void Main(){

         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();

只需注意

如果你需要这样做,那么你需要看看你的班级设计。以这种方式使用接口的想法是抽象出对象具体实现的细节。如果您必须执行这样的显式转换,那么您可能需要查看更改接口以适应必要的方法,或者更改类以便将方法移动到全局位置(如<$ c) $ c> 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).

额外阅读

您应该阅读有关参考类型的信息在哪里,你应该看一下here 。我的答案是对这两种情况的理解的结合。

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天全站免登陆