【问题标题】:It's Possible Interface internally inherit the Object Class可能接口内部继承了对象类
【发布时间】:2019-02-25 04:51:07
【问题描述】:

Interface 隐式继承 Object 类。因为接口SubInterfacedefault方法调用了ObjectclasshashCode方法。那么有可能如何&为什么..?

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

【问题讨论】:

标签: java object inheritance interface


【解决方案1】:

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

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

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

有一点需要注意,如果你查看 JLS spec

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

这就是为什么你可以打电话给SuperInterface.super.hashCode();

【讨论】:

  • 还有一个疑问。在这种情况下声明 SuperInterface.super.hashCode();
【解决方案2】:

InterfaceAbstractCombination 类的 hashCode 在您的继承层次结构中提供。 this 不属于接口,即使它有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());
    }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-24
    • 2019-01-05
    • 1970-01-01
    • 2014-06-01
    • 2021-09-12
    • 2013-01-09
    • 1970-01-01
    • 2020-10-09
    相关资源
    最近更新 更多