This is one of the toughest and trickiest question in java language. You may also know that only classes in java are inherited from java.lang.Object class.
Interfaces in java don’t inherit from Object class. They don’t have default parent like classes in java. But, following two cases may surprise you.
Case 1 : If an interface does not extend Object class, then why we can call methods of Object class on interface variable like below ?
Case 1 : If an interface does not extend Object class, then why we can call methods of Object class on interface variable like below ?
interface A
{
}
class InterfaceTest
{
public static void main(String[] args)
{
A a = null;
a.equals(null);
a.hashCode();
a.toString();
}
}
Case 2 : If an interface does not extend Object class, then why the methods of Object class are visible in interface.?
interface A
{
@Override
public boolean equals(Object obj);
@Override
public int hashCode();
@Override
public String toString();
}
Explanation :
Here is the answer, for every public method in Object class, there is an implicit abstract and public method declared in every interface which does not have direct super interfaces. This is the standard Java Language Specification which states like this,
“If an interface has no direct super interfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause to 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.”
Interface Members
The members of an interface are:
- Those members declared in the interface.
- Those members inherited from direct superinterfaces.
- 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.
It follows that is a compile-time error if the interface declares a method with a signature that is override-equivalent to a public method of Object, but has a different return type or incompatible throws clause.
It follows that is a compile-time error if the interface declares a method with a signature that is override-equivalent to a public method of Object, but has a different return type or incompatible throws clause.
Comments
Post a Comment