Interface与Object之间的关系问题


最近在想Interface与Object之间的关系问题?
我们都知道,在JAVA中,所有的类都是继承了Object类,但是接口呢?
在我们定义接口时,是不需要显示 extends java.lang Object
但是一个接口没有继承Object类,但我们在任何接口上调用Object类的方法,编译器都不报错,这种现象该如何解释呢?例如,下面的代码中 Runnable是一个接口,但我们针对这个接口调用了Object类的一些方法,可以成功通过编译,是不是编译器对这种情况进行了特殊对待?
class InterfaceAndObject
{
  public void interfaceTest(Runnable r)
  {
    System.out.println(r.toString() + r.hashCode());
  }
}

去看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中具有相同签名的方法时,编译器不会报错!
这段描述对我很有帮助,说了这么多,只是想让大家在空闲时间来考虑JAVA的设计思路和理念,巩固和加深对它的理解.

你可能感兴趣的:(sun)