接口内部可能继承对象类

时间:2019-02-25 04:51:07

标签: java object inheritance interface

接口隐式继承Object类。因为接口SubInterface default方法调用了ObjecthashCode方法。那么,为什么和为什么..?

package com.oca.test.exam;

    interface SuperInterface {
        default void printStuff() { System.out.println("Default Method"); }
    }

    interface SubInterface extends SuperInterface {
        default void doStuff() {
            this.printStuff();
            System.out.println(this.hashCode());
        }
    }

    public class InterfaceAbstractCombination implements SubInterface{

        public static void main(String[] args) {
            SubInterface sub = new InterfaceAbstractCombination();
            sub.doStuff();
        }
    }

2 个答案:

答案 0 :(得分:2)

接口没有继承Object类别。实现接口SubInterface的类继承了Object类。

考虑一下,您可以直接调用doStuff的{​​{1}}()吗?您需要在另一个类中实现该接口,创建该类的实例,然后才能调用SubInterface

因此doStuff()类实现了InterfaceAbstractCombination,当您调用SubInterface时,您是在doStuff()实例上调用它的,该实例提供了从{ InterfaceAbstractCombination类,因此this.hashCode()将引用实现该接口的类的实例。

要注意的一件事,如果您检查JLS spec

  

如果接口没有直接的超级接口,则该接口   隐式声明带有签名的公共抽象成员方法m   s,返回类型r和对应于每个public的throws子句t   具有签名s,返回类型r和throws子句t的实例方法m   在Object中声明,除非具有相同签名的方法,相同   返回类型,并由显式声明兼容的throws子句   界面。

这就是为什么您可以拨打Object的原因。

enter image description here

答案 1 :(得分:0)

您的继承层次结构中提供了hashCode类的InterfaceAbstractCombinationthis不属于接口,即使它具有default方法也是如此。

考虑在以下代码下运行,您会看到相同的hashCode打印出来:

package com.oca.test.exam;

  public class InterfaceAbstractCombination implements SubInterface {

    public static void main(String[] args) {
        SubInterface sub = new InterfaceAbstractCombination();
        sub.doStuff();
        System.out.println(sub.hashCode());
    }
    }

    interface SuperInterface {
    default void printStuff() {
        System.out.println("Default Method");
    }
    }

    interface SubInterface extends SuperInterface {
    default void doStuff() {
        this.printStuff();
        System.out.println(this.hashCode());
    }
    }