如果 Annotation 是一个接口,那么它如何扩展 Object 类? [英] If Annotation is an interface then how it can extend an Object class?

查看:23
本文介绍了如果 Annotation 是一个接口,那么它如何扩展 Object 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们将一个注解定义为一个接口,如下所示

We define an annotation as an interface as below

@interface annot_name {

}

而且我们知道所有的注解都默认扩展接口java.lang.annotation.Annotation.

and we know that all annotations extends interface java.lang.annotation.Annotation by default.

当我检查 Annotation 接口的 java 库时,我发现它覆盖了 Object 类的许多方法,如 hashCode() 等.

When I checked the java library for Annotation interface I found that it was overridding many methods of Object class like hashCode() etc.

如果 Annotation 是一个接口,那么它如何扩展 Object 类并覆盖其方法?接口只能扩展其他接口,不能扩展类.

If Annotation is an interface then how could it extend an Object class and override its methods? Interfaces can only extends other interfaces and not classes.

推荐答案

所以我的问题是如果 Annotation 是一个接口,那么它怎么会扩展一个 Object 类并覆盖它的方法

So my question is if Annotation is an interface then how could it extends an Object class and override its methods

不完全是.Java 语言规范 §9.2 说

如果一个接口没有直接的超级接口,那么接口隐式声明一个带有签名的public abstract成员方法ms,返回类型r,以及throws子句t对应每个public实例方法 m 带有签名 s、返回类型 rthrows 子句 tObject 中声明,除非方法具有相同的签名,相同返回类型,并且一个兼容的 throws 子句被显式声明为界面.

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.

所以任何 interface 都会得到这些方法.

So any interface gets those methods.

对于Annotation,设计者只是选择在源代码中重新声明它们,以便他们可以记录它们的行为.

For Annotation, the designers just chose to re-declare them in the source code so they could document their behavior.

这篇关于如果 Annotation 是一个接口,那么它如何扩展 Object 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆