首页 > 解决方案 > 可能接口内部继承了对象类

问题描述

Interface 隐式继承 Object 类。因为接口SubInterface defaultMethod调用了ObjecthashCodeMethod。那么有可能如何&为什么..?

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

标签: javaobjectinheritanceinterface

解决方案


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

想想看,能不能直接调用doStuff() of SubInterface?您需要在另一个类中实现该接口,创建该类的实例,然后您可以调用doStuff().

所以InterfaceAbstractCombination类实现了SubInterface,当你调用它时,doStuff()你调用它的实例InterfaceAbstractCombination是提供this.hashCode()从类继承的Object,所以this将引用实现接口的类的实例。

需要注意的一件事,如果您检查 JLS规范

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

所以这就是你可以打电话的原因SuperInterface.super.hashCode();

在此处输入图像描述


推荐阅读