gpt4 book ai didi

java - 编译器如何知道 obj.print(); 应该调用哪个打印方法?

转载 作者:行者123 更新时间:2023-11-30 08:34:01 25 4
gpt4 key购买 nike

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

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?
}
}

最佳答案

第一个问题:

实现满足两个契约,因此无论您将具体类转换为 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 有方法 #printShowable 有方法 #show,继承它们两者都会为您的程序添加功能。

如果你想结合几个具体类的功能,你可能想看看 composition instead of inheritance.

第二个问题的答案比较棘手。你可以找到更长的讨论here .虽然 Java 的创建者有可能加入这样的选项,但它会为一些非常困惑的代码打开大门。想一想您给出的示例:如果 PrintableShowable 具有 #print 方法的具体实现怎么办?继承类应该选择哪个实现?

关于java - 编译器如何知道 obj.print(); 应该调用哪个打印方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39115675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com