gpt4 book ai didi

java - 扩展类和实现接口(interface)之间的交互

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:34:49 24 4
gpt4 key购买 nike

public class Main {

public static class ClassBase {

public void test() {
System.out.println("1");
}

}

public static interface Interface {

default void test() {
System.out.println("2");
}

}

public static class MyClass extends ClassBase implements Interface {

}

public static void main(String[] args) {
new MyClass().test();
}

}

在这个例子中,它总是打印 1。要打印 2,我必须覆盖 MyClass 中的 test 并返回 Interface.super.test()

有没有办法让 Interface::test 方法覆盖 ClassBase::test 方法,而无需手动覆盖 MyClass 中的方法?(在示例中打印 2)

最佳答案

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.

结论:默认方法不能覆盖实例方法。

关于java - 扩展类和实现接口(interface)之间的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45110791/

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