日期:2014-05-20  浏览次数:20683 次

散分贴,关于interface和Object关系的思考!
其实这个问题讨论起来没什么意义,不过大半夜睡不着,写点东西散个分.

下面是一个最简单的interface:
interface   I   {}
这个   I   和   Object   到底有什么关系呢?

问题一:
public   class   T   {
public   static   void   main(String[]   args)   {
I   i;
}
}
上面一个简单的类,用eclipse的时候在I   i;下面面输入 "i. "会出现Object的方法列表.
显然即时编译器编译通过了才会出现这种结果.为什么?

问题二:
interface   Test   {
public   int   toString();
}
接口改成上面这个样子.编译后有如下错误:
Test.java:2:   Test   中的   toString()   无法覆盖   java.lang.Object   中的   toString();正在尝试使用不兼容的返回类型
找到:   int
需要:   java.lang.String
                public   int   toString();
                                      ^
1   错误

问题三:
再改改这个接口:
interface   Test   {
public   void   wait();
}
编译后有如下错误:
Test.java:2:   Test   中的   wait()   无法覆盖   java.lang.Object   中的   wait();被覆盖的方法为   final
                public   void   wait();
                                        ^
1   错误


要回答这三个问题,就先要回答interface和Object的关系.
从java程序设计语言的角度上将interface不是类,而Object是所有类的最终超类.
所以从这里看interface和Object没有必然联系.

但是看看java   language   specification中怎么说:
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.

It   follows   that   is   a   compile-time   error   if   the   interface   declares   a   method   with   a   signature   that   is   override-equivalent   (§8.4.2)   to   a   public   method   of   Object,   but   has   a   different   return   type   or   incompatible   throws   clause.

简单的说就是:
如果接口没有直接超接口,那么该接口会隐式声明一些public   abstract的方法,这些方法和Object中的public方法具有对应的方法签名,返回类型,异常列表.
如果在接口中显示声明了Object中的final的方法,报错.
如果在接口中声明的方法和Object中的方法具有相同的方法签名,但是返回类型不同或者异常列表不相容,报错.

按照上面的说法,给与了前三个问题合理的解释.
interface不是类,与Object的关系更谈不上继承.但它和Object的关系密切,它将Object的public方法都声明为了abstract.

但是问题并没有就此结束...
还是这个interface   I   {}
编译后javap   -verbose看看:
常量池Constant   pool:
const   #1   =   class                 #5;           //     I