我必须使用一个带有几个示例的API。在其中一个示例中,接口被直接用于调用该接口的方法之一。但是,由于interface不包含任何实现,我想知道:在没有定义实现该接口的类的情况下,如何在示例中使用这些方法来完成任何任务?
或者,接口也可以包含完整的方法定义吗?(这里看起来就是这样)
发布于 2010-01-26 18:49:03
不,接口只包含方法签名。接口中不能有实现。
在你的例子中(最有可能的)是类似于(伪代码):
InterfaceA {
methodA();
}
class A implements InterfaceA {
methodA() // implementation
}
InterfaceA getInterface() {
// some code which returns an object of a class which implements InterfaceA
}调用方法:
InterfaceA in = getInterface() // you might get an instance of class A or any other class which implements InterfaceA
in.methodA(); // implementation from whatever class the method returned发布于 2010-01-26 18:46:01
你的意思是像这样的..。
InterfaceA a = getInterface();
a.method();在本例中,a将是实现InterfaceA的类的实例-该类是什么并不重要,因为您所关心的只是接口方法。
发布于 2010-01-26 18:46:46
接口的
的原因
查看对象的创建位置。您可以拥有:
public void doSomething() {
MyInterface interface = new MyInterfaceImplementation();
doSomething(interface);
}
public void doSomethingElse(MyInterface interface) {
interface.someMethod();
}因此,通过查看doSomethingElse()方法,它可能看起来没有实现,但调用该方法的人提供了实现(本例中为MyInterfaceImplementation);
https://stackoverflow.com/questions/2138809
复制相似问题