Does Java interface implement an object?

Is 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, although I did not implement the equals method of this interface. Your answers make this clear. But does anyone know if the above is an anonymous local inner class or a named local inner class?

+3
source share
4 answers

Grade. Referring to Java Language Specifics :

If the interface does not have direct superinterfaces, then the interface implicitly declares a public annotation member method m with signature s, return type r, and a sentence th t corresponding to each public instance of method m with signature s, return type r and throws t declared in Object if only a method with the same signature, the same return type and compatible throw condition explicitly declared by the interface. This is a compile-time error if the interface explicitly declares such a method m in the case where m is declared final in the Object.

Note that Object has a number of final and protected methods that all interfaces “inherit” in this way, and you cannot have these modifiers in the interface (which will be implied by your “implements java.lang.Object”).

+7
source

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

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

+6
source

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

The whole point of the interface is that it does not contain implementation details. If an interface can extend a class, it inherits the implementation details of that class, which will lead to a point hit.

+2
source

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

+1
source

Source: https://habr.com/ru/post/1389201/


All Articles