Every Java developer knows that java.lang.Object serves as the root class for all Java class hierarchies. In that case, does java have a root interface for all interfaces ? If not, then how does java allow us to invoke equals method (or any other method defined in java.lang.Object) on an Interface reference ?
interface MyInterface {
}
class MyClass implements MyInterface {
public static void main(String[] args) {
MyInterface myInterface = new MyClass();
MyInterface yourInterface = new MyClass();
System.out.println(myInterface.equals(yourInterface));
}
}
In the above code snippet how am I able to call equals method on myInterface reference ?
Java Language Specificion says,
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 he same signature, same return type, and a compatible throws clause is explicitly declared by the interface.
Interestingly, if you try to declare an equals method like the following in an Interface, javac will complain.
interface test {
public int equals(Object o);
}
[root@unnisworld:/unni] javac test.java
test.java:4: equals(java.lang.Object) in test cannot override equals(java.lang.Object) in java.lang.Object; attempting to use incompatible return type
found : int
required: boolean
public int equals(Object o);
^
1 error





