【发布时间】: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