As per my understanding from some books on Java, interfaces cannot extend classes.
But all interfaces do inherit methods from Object class. Why is this so?
If Interface not extend from Object class. So how this code work it?
interface A
{
public boolean equals(Object o);
}
class InterfaceAndObjectClass
{
public static void main(String[] args)
{
A a = null;
a.equals(null);
a.hashCode();
a.toString();
}
}
Please help me to explain how access the Object class method in Interface.
Object is a class, and interfaces can not extend classes, so "no" - the interface doesn't inherit anything from any class.
Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing a common functionality to unrelated classes. Interfaces are a good choice when we think that the API will not change for a while.
The main advantages of interface over abstract class is to overcome the occurrence of diamond problem and achieve multiple inheritance. In java there is no solution provided for diamond problem using classes. For this reason multiple inheritance is block using classes in java.
An interface is better than a abstract class when you want multiple classes to implement that interface and when you don't have to inherit default behavior.
An interface implicitly contains all the methods of Object
class. And since any class that implements that interface is a sub-class of Object
, it contains the implementation of all those methods.
JLS 9.2
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 an abstract method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.
Eran is absolutely right. Actually Interface does not extend or implement Object class. It Implicitly contains all the methods of Object class. Note(further):
If you declare same (abstract) method(with same name-signature, return type, and throws type, compiler will consider it as overriding(its ok) but if you declared with different return type or different throws type compiler will will force you to keep same(compatible) return type or throws clause.
try to declare below equals method in your interface.
public int equals(Object obj);
//it will show compile time error return type is //not compatible. (it should be boolean not int)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With