gpt4 book ai didi

java - 重写 Java 接口(interface)中的对象类方法

转载 作者:搜寻专家 更新时间:2023-11-01 01:23:15 24 4
gpt4 key购买 nike

让我们考虑以下 Java 中的简单代码。

package temppkg;

interface Interface
{
@Override
public abstract boolean equals(java.lang.Object arg);

@Override
public abstract String toString();

public void show();
}

final class Demo implements Interface
{
public void show()
{
System.out.println("Method invoked.");
}
}

final public class Main
{
public static void main(String...args)
{
new Demo().show();
}
}

在上面的代码片段中,接口(interface)名为Interface有一些来自 JDK 的 Object 类方法,它们与 @Override 一起使用注释,即使它们是抽象的。现在,类(class) Demo已实现Interface并且没有实现equals()toString();方法。编译器仍然没有提示,程序运行成功。为什么?Java中的接口(interface)和对象类是什么关系?

最佳答案

The Java Language Specification clearly says that the members of an interface are those which are declared in the interface and those which are inherited from direct super interfaces. If an interface has no direct superinterface then the interface implicitly declares a public abstract member method corresponding to each public instance method declared in the Object class, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by that interface. This is what makes the signatures of the Object methods available to the compiler and the code compiles without any error. Remember if the interface tries to declare a public instance method declared 'final' in the Object class then it'll result into a compile-time error. For example, 'public final Class getClass()' is a public instance method declared 'final' in the Object class and therefore if an interface tries to declare a method with this signature then the compilation will fail.

http://geekexplains.blogspot.com/2008/06/do-interfaces-really-inherit-from-class.html

关于java - 重写 Java 接口(interface)中的对象类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8721848/

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