Joker
Joker

Reputation: 11146

Interafce vs abstract class in overriding object class methods

Following code is compiling absolutely fine.

To my understanding it should not be because Class C implementing interface I

as abstract class fails to compile as well.

interface I {
    public String toString();
}

class C implements I {

}

Abstract class is not compiling

abstract class MyAbstractClass {
    public abstract String toString();
}

public class MyClass extends MyAbstractClass {
}

Please help me understand this behavior why abstract is not compiling and interface does ?

Upvotes: 2

Views: 74

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

Every class implicitly extends java.lang.Object, and java.lang.Object implements the toString() method. The interface's contract is satisfied by that implementation, thus removing the need for your class to provide its own implementation of toString().

The reason compilation fails for the abstract class is because you explicitly define the toString() method as abstract, thereby signaling that concrete extending classes are forced to provide their own implementation.

Upvotes: 5

Related Questions