我们将注解定义为接口(interface),如下所示
@interface annot_name {
}
而且我们知道所有注解都默认扩展接口(interface)java.lang.annotation.Annotation
。
当我检查 java 库中的 Annotation
接口(interface)时,我发现它覆盖了 Object 类的许多方法,如 hashCode()
等。
如果 Annotation 是一个接口(interface),那么它如何扩展一个 Object 类并覆盖它的方法呢?接口(interface)只能扩展其他接口(interface)而不能扩展类。
最佳答案
So my question is if Annotation is an interface then how could it extends an Object class and override its methods
不完全是。 The Java Language Specification §9.2 says
If an interface has no direct superinterfaces, then the interface implicitly declares a
public abstract
member methodm
with signatures
, return typer
, andthrows
clauset
corresponding to eachpublic
instance methodm
with signatures
, return typer
, andthrows
clauset
declared inObject
, unless a method with the same signature, same return type, and a compatiblethrows
clause is explicitly declared by the interface.
所以任何 interface
都可以获取这些方法。
对于Annotation
,设计者只是选择在源代码中重新声明它们,以便记录它们的行为。
关于java - 如果 Annotation 是一个接口(interface),那么它如何扩展一个 Object 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27118951/