从超类继承方法的重要性,而不是从Java 8中实现接口继承默认方法的重要性 [英] Significance of inheriting method from superclass instead of default method from implementing interface in java 8

查看:129
本文介绍了从超类继承方法的重要性,而不是从Java 8中实现接口继承默认方法的重要性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从此处:

如果层次结构中的任何类都具有具有相同签名的方法,则默认方法将变得无关紧要.缺省方法不能覆盖java.lang.Object中的方法.推理非常简单,这是因为Object是所有java类的基类.因此,即使我们将Object类方法定义为接口中的默认方法,也将是无用的,因为将始终使用Object类方法.因此,为了避免混淆,我们不能使用覆盖Object类方法的默认方法.

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.

我迅速尝试了以下代码以确认行为

I quickly tried following code to confirm the behavior

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()

我看不到语言设计者选择此特定行为的任何具体原因.他们是我想念的重要理由吗?还是它的接口默认方法在逻辑上比超类提供的具体实现更不重要?

I am not able to see any specific reason behind why this particular behavior is chosen by language designer. Is their any such significant reason that I am missing? Or its just that interface default method logically bears lesser importance than concrete implementation provided by the super class?

推荐答案

答案很简单:可以实现多个interface,但可以扩展一个class.实际上,通过实现多个接口,您不能拥有多个具有相同名称的default方法.

Answer is simple: you are allowed to implement multiple interface but you can just extend one class. Indeed you can't have multiple default methods with the same name by implementing multiple interfaces.

如果在任何情况下default方法的优先级都比层次结构中真实类中实现的方法的优先级高,那么您最终会遇到相同的确切问题,而Java设计人员不希望它们具有多重继承:模糊性.

If in any circumstance a default method has higher priority than a method implemented inside a real class in the hierarchy you end up having the same exact problem for which Java designers didn't want multiple inheritance: ambiguity.

个人观点:默认方法被视为在未定义任何功能的情况下的实现",如果该方法是在真实类中定义的,则应该是更具体的实现.

As a personal opinion: a default method is seen as a "implementation of a functionality when none is defined", if the method is defined in a real class it is expected to be a more specific implementation.

这篇关于从超类继承方法的重要性,而不是从Java 8中实现接口继承默认方法的重要性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆