2013-04-09 78 views
-2

假设有2个类实现相同的接口和从该接口的方法。如果我直接从界面调用方法,决定返回哪个实现(从第一个或第二个类)是什么?当两个类实现相同的接口

+0

好了,你可以写一个示例代码,看看它自己。 – PermGenError 2013-04-09 16:09:46

+0

我在工作。我没有时间。 :D我认为有人可以说一般规则 – Madrugada 2013-04-09 16:10:24

+0

你是什么意思。除非指定具体类,否则如何实例化接口? – Patrick 2013-04-09 16:10:34

回答

8

你不直接从一个接口调用一个方法,而是在一个指向一个类的实例的引用上调用它。无论哪个类都决定调用哪个方法。

+0

至少你定义了一个[匿名类](http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm)。 – 2013-04-09 16:14:45

+0

@LuiggiMendoza我不知道你的意思。您仍然在这些对象上创建匿名类的实例并调用方法。 – 2013-04-09 16:16:27

+0

对不起,我的意思是说你可以创建一个匿名类来定义接口的一个新的实现,以实现它的任何实际类。 – 2013-04-09 16:18:42

0

接口不能有方法的主体/定义。所有的方法都是抽象的。你不能定义方法体,因此你不能从接口调用任何方法。

2

您可以通过执行实现接口的具体类的构造函数来定义接口的实例。

Interface interface = new ConcreteClass(); 
2
package test; 
    public interface InterfaceX { 
    int doubleInt(int i); 
} 

package test; 
public class ClassA implements InterfaceX{ 
    @Override 
    public int doubleInt(int i) { 
     return i+i; 
    } 
} 

package test; 
public class ClassB implements InterfaceX{ 
    @Override 
    public int doubleInt(int i) { 
     return 2*i; 
    } 
} 

package test; 
public class TestInterface { 
    public static void main(String... args) { 
     new TestInterface(); 
    } 
    public TestInterface() { 
     InterfaceX i1 = new ClassA(); 
     InterfaceX i2 = new ClassB(); 
     System.out.println("i1 is class "+i1.getClass().getName()); 
     System.out.println("i2 is class "+i2.getClass().getName()); 
    } 
} 
相关问题