java中interface是不是继承Object

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/afsvsv/article/details/79861168

疑问描述:

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


     很明显,是要判断是传进来的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);  }  

猜你喜欢

转载自blog.csdn.net/afsvsv/article/details/79861168