On compilation the above code gives "Compilation error" that , we have not overridden the toString() method correctly as Object class has toString() method with return type String.
But on second glance i felt that interfaces do not extend Object class then why this error is thrown by a Compiler.
Then after some thoughts i came to a conclusion that even interfaces do not extends Object class, they are ultimately to be implemented by some concrete class and in order to preserve the contract of interfaces and overriding rules of a class Object (as each class inherits from Object class implicitly ), it is mandatory to follow the same overriding rules of method declaration defined in class Object.
If the above hypothesis is true ? Then why i am getting NO COMPILER ERROR in the following ........but i really think it should because ultimately it is going to break the code.
Whatever I am writing below is just my assumption and simple logic I don't know the concrete answer
According to me interfaces do not extend Object class as I have not seen any interface that is written in java API
the finalize method in the interface that we are declaring is the method that is not known to the object class
that is.. there is not concept of overriding as Object class is not the parent of the interface that we are declaring (This is just my opinion)
so the compiler does not give any error while writing the method
i.e. the method can act as a separate method because the interface has not any super class
this is like two methods of the same name which are in different classes but they are private... the classes cannot see the private methods
and the declaration of the methods with the same name is allowed
I think similar case has happened here because the declared interface is not knowing the Object class and the finalize method in it
so it is free to declare a method with the same name
I hope I am correct
Happy learning Sahil.. you are going to rock in the exam by the way you are preparing
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.
Since toString is public in Object, the interface will have its implicit declaration but since finalize is protected, there will be no implicit declaration of finalize method in an interface...