现在的位置: 首页 > 综合 > 正文

请教Interface与Object之间的关系问题

2013年08月26日 ⁄ 综合 ⁄ 共 1683字 ⁄ 字号 评论关闭

请教Interface与Object之间的关系问题
一直没有读过什么经典的Java书籍,有时候被学员拿着《think in java》中一些看不懂的地方来问我,我才顺便跟着看上一页两页的。我现有的java知识都是零零散散收集的和在大量的教学实践中自我总结的,所以,我掌握的java知识体系不够系统。我现在有一个非常基础的问题,不知道有没有朋友能够给出权威的解释,最好能给出解释的原文出处,鄙人将不胜感激!
一个接口没有继承Object类,但我们在任何接口上调用Object类的方法,编译器都不报错,这种现象该如何解释呢?例如,下面的代码中Runnable是一个接口,但我们针对这个接口调用了Object类的一些方法,可以成功通过编译,是不是编译器对这种情况进行了特殊对待?
class InterfaceAndObject
{
 public void interfaceTest(Runnable r)
 {
  System.out.println(r.toString() + r.hashCode());
 }
}

----------------------------------------------------------------------------------

谢谢楼下各位的参与和帮助,特别感谢asfsd的提示,我去看了你提示的文章: http://community.csdn.net/Expert/TopicView3.asp?id=4902867
在这篇文章中,我看到了我想要的答案,如下:
回复人:dwys0343(特兰克斯) ( ) 信誉:100 2006-7-31 8:46:56 得分:0

去看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中具有相同签名的方法时,编译器不会报错!这段描述对我很有帮助,以至我又想出了一个新的问题,来巩固和加深对它的理解.

interface InterfaceTest
{
 /*boolean*/int equals(Object obj);
}

编译上面的接口时,将报告如下错误:

InterfaceTest.java:3:equals(java.lang.Object) in InterfaceTest cannot override equals(java.lang.Object) in java.lang.Object; attempting to use incompatible return type
found   : int
required: boolean
        /*boolean*/int equals(Object obj);
                       ^
1 error

 

抱歉!评论已关闭.