Tuesday, May 3, 2011

implicit super-interface in Java?

So we all know that all classes implicitly extend Object. How about interfaces? Is there an implicit super-interface? I say there is. The following code compiles:

java.io.Serializable s1 = null;
java.io.Serializable s2 = null;

s1.equals(s2);

The equals method is not declared in Serializable, but in Object. Since interfaces can only extend other interfaces, and Object is a class, not an interface, there must be some implicit interface that is being extended. And the Object class must then implicitly implement this implicit interface (wow, that was weird to write).

So, the question is, how correct is this?

From stackoverflow
  • s1 and s2 here are object references, referring to instances of objects that implement Serializable. There is no such thing as an interface reference in Java.

    So Java knows that whatever these objects are, they descend from java.lang.Object. Hence the above code is valid.

  • When you declare something like:

    java.io.Serializable s1 = null;
    

    don't forget that everything in Java is derived from Object. So here, you are only saying that s1 is something (either Object or some class extending Object) that implements Serializable. There is no magic. Everything in Java is derived from Object whether it is explicit or not. Thus, the equals method is always available.

    McWafflestix : maybe I'm missing something, but how is declaring a variable "declaring a type"?
    Eddie : OK, I worded it poorly. Let me edit and try again.
  • I don't think there's any super interface.

    When you declare a variable like this:

    java.io.Serializable s1 = null;
    

    you haven't created any Object.

    The compiler knows that s1 and s2 will implement Serializable and will descend from Object so it allows the equals.

  • Since interfaces can only extend other interfaces, and Object is a class, not an interface, there must be some implicit interface that is being extended.

    No. Citing the Java Language Specification:

    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.

    The difference between this and your "implicit super interface" is that Object has a number of final and protected methods, and you couldn't have those modifiers in an interface.

    Michael Myers : +1 for actually citing the spec.

0 comments:

Post a Comment