扩展 class 和实现接口之间的交互
Interaction between extended class and implemented interface
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
和 return Interface.super.test()
.
中的 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.
结论:默认方法不能覆盖实例方法
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
和 return Interface.super.test()
.
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.
结论:默认方法不能覆盖实例方法