ace
ace

Reputation: 12034

Java Interface implements Object?

Does any Java Interface implicitly implements java.lang.Object?

This question arose when I did something like this:

public static String[] sizeSort(String[] sa) {

Comparator<String> c = new Comparator<String>() {
            public int compare(String a, String b) {
                if (a.length() > b.length()) return 1; 
                else if (a.length() < b.length())
                    return -1;
                else 
                    return 0;
                 }
        };

// more code

}

It worked fine even though I did not implement equals method of this interface. Your answers clears this up. But does any one know if above is anonymous local inner class or named local inner class?

Upvotes: 3

Views: 2715

Answers (4)

Matthew Farwell
Matthew Farwell

Reputation: 61705

java.lang.Object is not an interface, so no interface will implicitly implement it.

However, any class that you create which implements any interface will extend Object, because all classes must extend it. Any instance which you (or indeed anyone else) can create will therefore have all of the methods defined on java.lang.Object.

Upvotes: 6

Michael Borgwardt
Michael Borgwardt

Reputation: 346387

Sort of. 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.

Note that Object has a number of final and protected methods that all interfaces "inherit" this way, and you couldn't have those modifiers in an interface (which would be implied by your "implements java.lang.Object").

Upvotes: 7

Wyzard
Wyzard

Reputation: 34573

Object is a class, not an interface, so it can't be "implemented" by other interfaces.

The whole point of an interface is that it contains no implementation details. If an interface could extend a class, it would inherit that class's implementation details, which would defeat the point.

Upvotes: 2

A.H.
A.H.

Reputation: 66263

Strictly speaking: How would you know the difference? You will never have a reference to an interface, you will always having a reference to an actual instance with is an Object and implements the interface. This means that you can call methods from Object on any reference (not null of course) even if the declared type of the reference is an interface.

Upvotes: 1

Related Questions