2

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 ?

Kaan
  • 5,434
  • 3
  • 19
  • 41
T-Bag
  • 10,916
  • 3
  • 54
  • 118

1 Answers1

5

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.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • But abstract is compiling fine , I have edited my question please check – T-Bag Dec 12 '19 at 10:00
  • 3
    Yes, it's failing for the abstract class because you explicitly defined the `toString()` method as abstract, thereby forcing extending classes to implement it. – Robby Cornelissen Dec 12 '19 at 10:12
  • 2
    MyAbstractClass is failing because 'public abstract String toString()' is a new method you created and should be implemented in child classes. But 'public String toString()' in your interface is a method from Object class and you're just overriding it in your interface I – Yohan E Dec 12 '19 at 10:13
  • Thanks got it can you please share this as answer – T-Bag Dec 12 '19 at 10:14