Why Object class methods are available in interface?

前端 未结 5 1481
故里飘歌
故里飘歌 2021-01-24 23:25

Following interface and classes are successfully compiled. Problem is mentioned in the output below :

interface MyInterface{}

class MyClass imp         


        
相关标签:
5条回答
  • 2021-01-24 23:57

    Yes, all Object's methods are available to everything but Primitive value. Interface objects are still objects so they have Object's methods.

    0 讨论(0)
  • 2021-01-24 23:57

    The Java Language Specification clearly says that the members of an interface are those which are declared in the interface and those which are inherited from direct super interfaces. If an interface has no direct superinterface then the interface implicitly declares a public abstract member method corresponding to each public instance method declared in the Object class, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by that interface.

    0 讨论(0)
  • 2021-01-24 23:59

    The cast (Object)mi will always succeed so why should you be required to provide it?

    0 讨论(0)
  • 2021-01-25 00:00

    At run time there should be a real object (or null) behind the reference mi. The real type will implement this interface hence the compiler allows it. At run time any type that implements that interface could be there.

    0 讨论(0)
  • 2021-01-25 00:02

    What you are correctly pointing out as an exception is specified in the Java Language Specification. Interfaces will automatically get all members from the class java.lang.Object added. From here:

    The Java Language Specification clearly says that the members of an interface are those which are declared in the interface and those which are inherited from direct super interfaces. If an interface has no direct superinterface then the interface implicitly declares a public abstract member method corresponding to each public instance method declared in the Object class, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by that interface. This is what makes the signatures of the Object methods available to the compiler and the code compiles without any error. Remember if the interface tries to declare a public instance method declared 'final' in the Object class then it'll result into a compile-time error. For example, 'public final Class getClass()' is a public instance method declared 'final' in the Object class and therefore if an interface tries to declare a method with this signature then the compilation will fail.

    0 讨论(0)
提交回复
热议问题