java - 可能接口内部继承了对象类
问题描述
Interface 隐式继承 Object 类。因为接口SubInterface
default
Method调用了Object
类hashCode
Method。那么有可能如何&为什么..?
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();
}
}
解决方案
接口没有继承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();
。
推荐阅读
- python - cv2.matchTemplate 在图像中找到错误的模板
- list - 分而治之的乘法问题c ++
- docker - Docker CMD 在容器内的后台运行 bash 脚本
- asp.net - 如何为 DataGridView 创建自增列?
- c# - Visual Studio 中非常慢的编译程序执行时间与执行时间(附加调试器)
- c# - 如何确定单帧 DICOM 是否实际上是 MRI 切片?
- dspace - 更改语言时出现 DSpace 内部错误
- winforms - 如何为 WinForms 应用创建 MSIX 包?
- excel - 清理 VBA 代码以引用代码而不是复制它
- java - Android firebase 收藏按钮更改