java中interface是不是继承Object

疑问描述:

在如下代码的时候,不是很理解,为什么这么判断?


     很明显,是要判断是传进来的method的声明类是接口还是实现类,但是为什么直接用Object来判断呢?好像一直也没有去思考过这个问题,好尴尬,于是查阅资料,看看interface是不是继承Object.

    Sun的官方文档TJLS(The Java Language Specification)第9章9.2节关于接口描述如下: 

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. 

    大概翻译如下:如果一个接口没有直接顶级父接口,除非在该接口中明确的声明了方法,则会隐含得声明一套和Object中的方法签名完全一样的方法,并且,如果该接口明确声明一个和Object中用final方法一样的,则会报编译时异常。

     这样做的好处是,我们在程序中调用接口的那些与Object中具有相同签名的方法(toString,equal....)时,编译器不会报错。但是需要主要的是,是签名完全一样的方法,所以,return type也必须和Object里面的一样,否则也会报错。如下:

       public interface testInter{  /*String*/ void toString();  /*boolean*/ int equals(Object obj);  }  

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值