【问题标题】:Where are these methods being called from? [duplicate]这些方法是从哪里调用的? [复制]
【发布时间】:2017-10-28 11:11:23
【问题描述】:

好的,所以考虑一个接口

interface Action {
    void doSomething();
}

还有一个实现接口的类

class Greeting implements Action {

    public String getGreeting() {
        return "Hello, World!" ;
    }

    public void doSomething() {
        System.out.println(getGreeting());
    }

}

现在,如果我创建接口的引用并将其分配给类的对象

Action action = new Greeting();
action.doSomething(); // Calls the getGreeting() method and prints it.

这是如何工作的?

【问题讨论】:

  • 您已经明确要求只提供接口,Actions,当您这样做时:Action action = new Greeting();。使用该接口的子类实现的任何其他方法都是禁止的。
  • 你从动作类型定义动作变量,所以看不到 getGreeting() 方法。在 Greeting 类中,方法 getGreeting() 可以作为本地方法访问。
  • Greeting implements Actions。不应该是Action 而不是Actions

标签: java methods scope polymorphism


【解决方案1】:

您已经声明了Action 类型的变量action

这意味着您只能使用属于该接口的方法。

当你调用它时,它被委托给你的实现,即Greeting

【讨论】:

    【解决方案2】:

    您看到该错误是因为 action 属于 Action 类型,并且该类型没有 getGreeting() 方法。

    如果您需要访问getGreeting(),请将action 声明为Greeting

    Greeting action = new Greeting();
    action.getGreeting(); //should work
    

    或将action 转换为Greeting

    Action action = new Greeting();
    ((Greeting)action).getGreeting(); //Again, should work
    

    【讨论】:

      【解决方案3】:

      您已将Greeting 的对象分配给Action 类型。虽然Greeting的对象有getGreeting()的方法,但是Action类型不理解。

      这就是你尝试Action 对象时,不支持getGreeting 方法的原因。

      【讨论】:

        猜你喜欢
        • 2016-07-23
        • 1970-01-01
        • 1970-01-01
        • 2011-06-14
        • 2021-12-14
        • 2020-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多