interface 和Object的关系

    先看一个关于接口的测试代码:
  1. /**
  2.  *
  3.  * @author ZangXT
  4.  */
  5. interface Test {
  6.     public void test();
  7.     @Override
  8.     public int hashCode();
  9.     @Override
  10.     public String toString();
  11. }
  12. class TestInterface implements Test {
  13.     public void test() {
  14.     }
  15. }
  16. public class Main {
  17.     public static void main(String[] args) {
  18.         Object obj = new Object();
  19.         Test test = new TestInterface();
  20.         System.out.println(test.toString());
  21.         System.out.println(test.hashCode());
  22.         System.out.println(test.equals(test));
  23.     }
  24. }
     我故意保留了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"),还是不了解编译器具体是如何处理的.希望随着学习的深入能解决这个问题.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值