gpt4 book ai didi

java - java 8中从父类(super class)继承方法而不是从实现接口(interface)继承默认方法的意义

转载 作者:行者123 更新时间:2023-12-02 00:40:34 24 4
gpt4 key购买 nike

我在阅读 here 中有关 java 8 默认方法时遇到了以下段落:

If any class in the hierarchy has a method with same signature, then default methods become irrelevant. A default method cannot override a method from java.lang.Object. The reasoning is very simple, it’s because Object is the base class for all the java classes. So even if we have Object class methods defined as default methods in interfaces, it will be useless because Object class method will always be used. That’s why to avoid confusion, we can’t have default methods that are overriding Object class methods.

我很快尝试了以下代码来确认行为

public class DefaultMethodClass {
public void defaultMethod()
{
System.out.println("DefaultMethodClass.defaultMethod()");
}
}

public interface DefaultMethodInterface {
public default void defaultMethod()
{
System.out.println("DefaultMethodInterface.defaultMethod()");
}
}

public class DefaultMethodClassInterfaceChild extends DefaultMethodClass implements DefaultMethodInterface
{
public static void main(String[] args) {
(new DefaultMethodClassInterfaceChild()).defaultMethod();
}
}

这会打印

DefaultMethodClass.defaultMethod()

我看不出语言设计者选择这种特定行为背后的任何具体原因。他们有什么重要的原因让我失踪吗?或者只是接口(interface)默认方法在逻辑上比父类(super class)提供的具体实现更不重要?

最佳答案

I am not able to see any specific reason behind why this particular behavior is chosen by language designer.

方法定义是在 Java 1.0 中,接口(interface)默认方法是在 Java 8 中添加的。为 Java 1.0 编写的代码仍然需要工作。

Or its just that interface default method logically bears lesser importance than concrete implementation provided by the super class?

实际上,在现有代码编写了 20 多年之后,添加它们的重要性已降低。

关于java - java 8中从父类(super class)继承方法而不是从实现接口(interface)继承默认方法的意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57944355/

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