java 当两个类实现相同的接口时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15907040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:14:55  来源:igfitidea点击:

When two classes implement the same interface

javainterface

提问by Madrugada

Suppose there are 2 classes which implement a same interface and the methods from that interface. If I call a method directly from the interface, what is what decides which implementation will be returned (from first or second class) ?

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

回答by Bill the Lizard

You don't call a method directly from an interface, you call it on a reference that points to an instance of a class. Whichever class that is determines which method gets called.

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

回答by Michael Besteck

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());
    }
}

回答by Gilbert Le Blanc

You define the instance of an interface by executing the constructor of a concrete class that implements the interface.

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

Interface interface = new ConcreteClass();

回答by Vishy

interface cannot have body/definition for the method. All the methods are abstract. You cannot define method body, hence you cannot call any method from interface.

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