gpt4 book ai didi

java - 试图理解隐式 super 接口(interface)

转载 作者:行者123 更新时间:2023-11-30 11:40:59 25 4
gpt4 key购买 nike

抱歉带回 dead .但是我还是不太明白这一段规范是怎么说的。

If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface. It is a compile-time error if the interface explicitly declares such a method m in the case where m is declared to be final in Object.

给定

interface Testing
{
void test();
}
public class Test{
public static void main(String[] args) {
Testing t = new Testing(){
@Override
public void test(){
}
};
t.test();
t.toString();
}
}

现在,正如规范所述,上面的内容将更改为

    interface Testing
{
void test();
String toString();
//other non-final methods of Object
}
public class Test{
public static void main(String[] args) {
Testing t = new Testing(){
@Override
public void test(){
}
};
t.test();
t.toString();
}
}

还有。请确认是否存在接口(interface)层次结构,然后所有接口(interface)都获得这些抽象方法。

最佳答案

这意味着每个类都扩展了 Object(在其类层次结构中的某个点)。但是,接口(interface)不扩展对象。这是为了避免多重继承带来的问题。

由于接口(interface)不扩展 Object 这意味着如果我们可以访问的对象的类型(不是类)是界面。但我们知道这些方法必须可用,因为所有类在某个时候都从 Object 扩展而来。因此,为了解决这个问题,Object 的所有非 final方法都在没有超接口(interface)的所有接口(interface)中隐式声明。这些方法的这些契约总是得到满足,因为所有类都必须在某个时候从 Object 扩展。

TL;DR——当我们将某个类的实例存储在类型为接口(interface)的变量中时,确保我们可以访问 Object 提供的方法是一个技巧(例如。可序列化)

编辑:为了回答您的问题,您有点偏离了。 Object 的所有非 final方法都被添加到一个接口(interface)(无论它们是否被使用),如果该接口(interface)没有父接口(interface)并且对于每个要添加的方法:没有显式声明匹配的方法通过界面。

关于java - 试图理解隐式 super 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12456127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com