interface和Object的关系
来源:优易学  2011-12-8 11:34:47   【优易学:中国教育考试门户网】   资料下载   IT书店
  先看一个关于接口的测试代码:
  /**
  *
  * @author examda
  */
  interface Test {
  public void test();
  @Override
  public int hashCode();
  @Override
  public String toString();
  }
  class TestInterface implements Test {
  public void test() {
  }
  }
  public class Main {
  public static void main(String[] args) {
  Object obj = new Object();
  Test test = new TestInterface();
  System.out.println(test.toString());
  System.out.println(test.hashCode());
  System.out.println(test.equals(test));
  }
  }
  我故意保留了NetBeans IDE帮我生成的 @Override标记.这个地方看起来有些怪,按ide的提示,好像接口定义中的hashCode()方法和toString()方法重写了Object中的对应方法,不过我感觉这么理解很容易给人造成一种混乱,或者假象.例子中还可以看出,通过接口定义的引用变量,可以直接使用Object中定义的方法.
  为什么呢?
  初学的时候接受了The Java Programming Language一书的说法,
  You can invoke any of the Object methods using a reference of an interface type because no matter what interfaces the object implements, it is always an Object and so has those methods. In fact, any interface that does not extend some other interface implicitly has members matching each of the public methods of Object (unless the interface explicitly overrides them).
  后面也简单提了一下实现机制.Java语言规范中说的比较清楚:
  The members of an interface are:
  Those members declared in the interface.
  Those members inherited from direct superinterfaces.
  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.
  The interface inherits, from the interfaces it extends, all members of those interfaces, except for fields, classes, and interfaces that it hides and methods that it overrides.
  原来如此!
  奇怪的是,反编译接口的class文件并没有发现什么特殊的地方(除了常量池中能看到"java.lang.Object"),还是不了解编译器具体是如何处理的.希望随着学习的深入能解决这个问题

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训