Java: Do interfaces inherit from Object?

Interfaces do not inherit from Object. And there is no common “root” interface implicitly inherited by all interfaces either as in the case with classes.(*)

What may seem surprising is that it’s still possible to call Object methods (such as toString, hashCode etc) even on interface types.

Serializable s = "";
s.toStringCompiles even though Serializable neither
declares toString nor inherits from Object.
();

Formally, this is because each interface implicitly declares one method for each public method in Object. This is explained in detail in the Java Language Specification:

9.2 Interface Members

[…]

  • 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.

[…]JLS 9.2

(*) Note that the notion of being a subtype of is not equivalent to inherits from: Interfaces with no super interface are indeed subtypes of Object (§ 4.10.2. Subtyping among Class and Interface Types) even though they do not inherit from Object.

Comments (3)

The question is very interesting, however the above example is not right: you will see that s.getClass().getName() will show java.lang.String, so you are talking about the method toString() from java.lang.String class, not from java.lang.Object.

by Silviu | 
Reply

The Serializable-example is just to illustrate something that compiles and doesn't relate to the preceding sentence, but I can see how it's a bit confusing. Regardless by replacing "" with new Object() you would actually call Object.toString, so no factual error in the text.

by Andreas Lundblad | 
Reply

After a deeper thinking I realized I was wrong in my above comment. I guess too much IDE made me forget about "compile time" meaning. Thank you for reminding me.

by Silviu | 
Reply

Add comment