0

Does interfaces and abstract classes in Java extend base Object class? Logical answer which I can think of is no, but if interface does not extend Object class, then can please someone explain me the below code:

interface A { 

@Override 
public int hashCode(); 

@Override 
public String toString(); 

} 

In above case, A interface is the new interface declared. Yet, no class is implementing it. Then how come the methods from Object class visible in the interface?

If it doesn't extend Object class, then why I can't declare following method in the interface:

public Class getClass();

When I tried to declare this method in the interface, it says that it can't override this method, inherited from Object class, as it is declared as final method in Object class.

Denis Kulagin
  • 8,472
  • 17
  • 60
  • 129
LearningBasics
  • 660
  • 1
  • 7
  • 24

2 Answers2

1

Interface could only extend some other interface and no - there is no some root interface. Abstract class, as any other class in Java, has Object as its ancestor - while it may not be a direct parent.

Methods, marked as final, could not be overriden in successor classes. As your class has Object as its ancestor - this rule also applies here.

Denis Kulagin
  • 8,472
  • 17
  • 60
  • 129
0

The reason this is can be found in 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 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.

And as seen in Object#getClass:

public final Class<?> getClass()

Interfaces do not inherit from Object, but they do mimick the methods available by implicitly adding them. Likewise here, a final method in that base interface can't be overridden in your self-defined interface.

Community
  • 1
  • 1
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170