A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

葛尧

中级黑马

  • 黑马币:0

  • 帖子:70

  • 精华:0

接口引用指向子类对象为什么可以用equals() toString() hashCode()等方法?


不是说接口里面只能有抽象方法吗?interface 搞出来的自定义接口和Object有什么关系?

百度了一下,有说法interface出来的接口,可能有隐式继承了所有接口的上帝接口?该接口声明了Object里的所有方法? 这样虽然感觉说得通,那么不知道有没有什么证据?

例子:
  1. interface Inter
  2. {
  3. }

  4. class InterImpl implements Inter
  5. {
  6. }

  7. class Demo
  8. {
  9.         public static void main(String [] args)
  10.         {
  11.                 Inter i = new InterImpl();
  12.                 //打印的是子类的类名@hashcode,这点可以理解多态
  13.                 //郁闷的就是i里面只能有声明,并且Inter明显不能继承Object,怎么可以调toString()等?
  14.                 System.out.println(i.toString());
  15.                 System.out.println(i.equals(i));
  16.                 System.out.println(i.hashCode());
  17.         }
  18. }
复制代码

3 个回复

倒序浏览
本帖最后由 魏涞 于 2012-5-24 23:30 编辑

LZ是否这样考虑过,你要实现一个接口,是用一个类去实现,类 Object 是类层次结构的根类。每个类都使用 Object 作为超类。所有对象(包括数组)都实现这个类的方法。这样LZ可以理解了吧。
回复 使用道具 举报
你用来实现借口的类他就是一个类,只要是类就继承Object
回复 使用道具 举报
{:soso_e140:}很可惜都是答非所问。。 你们都答成子类与Object的关系了,我是问的接口。。
接口的定义有自己的一套标准,虽然编译出来也是字节码文件。。接口中不能有非抽象方法,所以肯定和Object类没有继承关系,但是能通过接口引用来调用子类对象中继承的Object类的方法,所以应该有其他形式的关系。

以下收搜索出来的解释:
     
去看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是一种特殊类,不继承自Object,但是编译器在编译时期做了手脚把 接口类型引用 处理为 子类对象引用。。看来想探究深层一点,要学点编译器等一类底层知识了。

评分

参与人数 1技术分 +1 收起 理由
攻城狮 + 1 赞一个!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马