Java 编译器如何知道obj.print()应调用哪个print方法;?

Java 编译器如何知道obj.print()应调用哪个print方法;?,java,interface,Java,Interface,这是一个显示多重继承的接口示例。我想知道如何通过接口实现多重继承,为什么不能通过类使用它 interface Printable // interface1 { void print(); } interface Showable //interface2 { void print(); } class TestTnterface1 implements Printable,Showable { public void print() {

这是一个显示多重继承的接口示例。我想知道如何通过接口实现多重继承,为什么不能通过类使用它

interface Printable // interface1
{  
    void print();  
} 

interface Showable //interface2
{  
    void print();  
}  

class TestTnterface1 implements Printable,Showable
{  
    public void print()
{
    System.out.println("Hello");
}  

public static void main(String args[])
{  
    TestTnterface1 obj = new TestTnterface1();  
    obj.print();  //which print method will be called now?
}  
}  

只有一个具体的方法可以调用

i、 e


在任何情况下,运行时都将调用
TestTnterface1#print()
方法,因为它是实现(可以执行的代码)


接口
契约实现的类必须遵循该契约,并且仅在编译时使用。编译器会检查实现者是否有(非抽象)具有相同名称和签名的方法。

因为两个接口都有print()方法,TestInterface1类有其实现,它将调用其实现

public void print()
{
    System.out.println("Hello");
} 
第一个问题:

实现满足这两个契约,因此无论您将具体类强制转换为
Printable
还是
Showable
,都将使用相同的方法。您会注意到有一种“不可能”的情况,如下所示:

public interface Printable{
    String print();
}

public interface Showable{
    void print();
}

public class Impl implements Printable,Showable{
    /*impossible to implement because you cannot have the same method signature with two different return types*/
}
多重继承通常意味着每个父代都添加了一些有用的东西。例如,如果
Printable
将具有方法
#print
Showable
将具有方法
#show
,继承它们将为程序添加功能

如果您想将几个具体类中的功能组合起来,您可能需要研究


第二个问题的答案更为棘手。你可以找到一个更长的讨论。虽然Java的创建者有可能加入这样的选项,但它会为一些相当混乱的代码打开大门。想想你给出的例子:如果
Printable
Showable
#print
方法的具体实现,会怎么样?继承类应该选择哪个实现?

问题1:调用哪个方法

实际上只能调用一个方法实现。因此,没有歧义

问题2:如何通过接口实现多重继承

你已经举了一个例子。这种继承的特殊之处在于不能有多个实现(直到Java7)。相反,Java8允许在接口中使用默认方法

问题3:为什么我们不能在课堂上使用它

interface Printable // interface1
{  
    void print();  
} 

interface Showable //interface2
{  
    void print();  
}  

class TestTnterface1 implements Printable,Showable
{  
    public void print()
{
    System.out.println("Hello");
}  

public static void main(String args[])
{  
    TestTnterface1 obj = new TestTnterface1();  
    obj.print();  //which print method will be called now?
}  
}  
它避免了国家的继承


提供更多信息。

它将调用
TestTnterface1.print()
。接口与此无关。您可以删除
实现可打印、可显示的
,它仍将编译,执行时仍将调用
TestTnterface1.print()
。为什么在运行时这两个方法都没有歧义?请简要解释。@Mayank Dudeja,因为接口中的方法没有代码(确切地说,在Java8之前)。因此,在运行时没有歧义。在运行时只有一个实现(一个类中不能有多个具有相同签名的方法)。