Interface与Object之间的关系问题

来源:互联网 发布:网络视频会议摄像头 编辑:程序博客网 时间:2024/04/28 20:32

举例:
interface A{

}
public class B implements A{
public static void main(String [] args){
A a = new B();
System.out.println(a.toString());
}
}

为什么可以调用不属于接口A的toString()方法?

注释

1   所有的类都默认继承自Object,那接口呢??

2  在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 

即说明了隐含Object类的存在??

3  接口是否是Object

不是。但可以用一个接口型的变量来引用一个对象??,而且,被引用的对象,说到底,一定是一个 Object。

4  多态性,上溯造型引用、接口回调??

5   看这段话:
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中具有相同签名的方法时,编译器不会报错!

101%的错误.

顶级接口对于程序员而言是没有任何方法可以调用的,但在jvm中它必须能被反射.上面这段话本来是说在JVM内总顶级接口会实现必要的方法来返回它的类型等相关信息.这和本主题没有任何关系.

至于这个主题的问题,大多数人理解是正确的,虽然他们没有深入理解JVM的底层实现,但java中一切都承继自Object,这是不用置疑的.
顶级接口也继承Object,所以上面的问题一点也不奇怪.在JVM内部它有其它类的正常行为.就象所有类在JVM内部都有<init>方法,那是用于JVM内部自省的功能,不是给程序员调用的.顶级接口在JVM内部仅仅是一个普通的Object子类,而它展示给程序员时就是一种特殊约束的调用.

无论如何,一个接口是继承Object的,只要理解这个句话其它一切都已经不是问题:

解开JAVA_HOME/jre/lib/rt.jar中的java/lang/Runnable.class放到d盘下:
运行class analyzer,得到结果:

magic number = 0xCAFEBABE
Version = 49.0
constant pool size = 9

const index = 1, flag = 1
const type = Utf8
length = 3

原创粉丝点击