- /**
- *
- * @author ZangXT
- */
- 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));
- }
- }
为什么呢?
初学的时候接受了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"),还是不了解编译器具体是如何处理的.希望随着学习的深入能解决这个问题.