我有一个界面Interface1
。我有它的实现Imple implements Interface1
(所有方法都已实现:))。
现在,考虑第三课CheckCall
,我可以在课程CheckCall
中拨打电话,如下所述:
Interface1 interface1;
interface1.method();
已完成所有必要的进口。请告诉我是否有可能,如果没有,那么确定如果是,那么告诉我如果我为同一个接口实现多个实现类并且我正在进行相同的调用会发生什么。
答案 0 :(得分:14)
好吧,你不能直接在界面上调用这个方法,但你可以做或多或少的写作。
您写道:
Interface1 interface1;
interface1.method();
如果您这样做,这将有效:
Interface1 interface1 = new CheckCall();
interface1.method();
然后告诉我如果我会发生什么 有多个impl类 相同的界面,我正在做的 同样的电话
嗯,这是关于Java的好处:你所指的问题被称为“钻石问题”:
http://en.wikipedia.org/wiki/Diamond_problem
它并不存在于Java中,因为Java完全支持多重继承,但只能通过“多(Java)接口继承”(*参见注释)。
因此,在您拨打interface1.method()
的情况下,您要么调用Impl
的方法,要么CheckCall
的方法,并且不会产生混淆。
答案 1 :(得分:7)
当然,您的代码运行正常!您只需使用实际实现(即新的Imple())初始化变量interface1
。
查看此示例,我使用了您的类名:
public class CheckCall {
interface Interface1 {
void method();
}
static class Imple implements Interface1 {
@Override
public void method() {
System.out.println("Imple.method1()");
}
}
public static void main(String[] args) {
Interface1 interface1;
interface1 = new Imple();
interface1.method();
}
}
答案 2 :(得分:5)
是的,但不是你写的。你不得不说:
Interface1 interface1 = new Imple();
您可以创建一个Interface类型的变量,然后将其实例化为实现该接口的类。您经常使用Java集合来看到这一点,例如:
List<String> a = new ArrayList<String>();
答案 3 :(得分:1)
实际上,您应该通过定义它们的接口来引用方法,但是您需要一个实际的实现类。所以我通常会这样做:
// the variable is of type Interface1
Interface1 interface1 = new Imple();
// but the method will be executed on the Imple object
interface1.method();
答案 4 :(得分:0)
不,您需要对实现接口的对象进行调用,而不是在接口本身上进行调用。
编辑:可以使用具有该类型的变量,但它仍然需要是实现该类型的类。您无法创建接口实例。
答案 5 :(得分:0)
没有
由于您无法实现界面,因此您必须创建一个Imple
对象,将其用作Interface1
这样的对象:
Interface1 interface1 = new Imple();
interface1.method();
实际上,接口的主要兴趣来自于让方法返回实现它的任何对象的能力,而不必担心给定的实现。在你的情况下,它可以显示为
public class CheckCall {
public Interface1 factoryMethod() {
return new Imple();
}
public void test() {
Interface1 used = factoryMethod();
used.method();
}
}