Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why make Abstract classes and Interfaces?

Well I was going to ask what the difference is but it's been answered before. But now I'm asking why did they make these differences? (I'm speaking about java here, I don't know if the same applies to other languages)

The two things seem very similar. Abstract classes can define a method body whilst interfaces can't, but multiple interfaces can be inherited. So why didn't they (by 'they' I mean Sun when they wrote Java) make one thing where you can write a method body and this type can be inherited more than once by a class.

Is there some advantage in not being able to write a method body, or extend multiple times that I'm not seeing?

like image 704
Paul Avatar asked Mar 03 '10 11:03

Paul


People also ask

What is the purpose of creating an abstract class?

The purpose of an abstract class is to provide a blueprint for derived classes and set some rules that the derived classes must implement when they inherit an abstract class. We can use an abstract class as a base class and all derived classes must implement abstract definitions.

What is advantage of using interfaces over abstract classes?

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.


1 Answers

Because allowing classes to inherit multiple implementations for the same method signature leads to the obvious question, which one should be used at runtime.

Java avoids this by supporting multiple inheritance only for interfaces. The signatures declared in each interface can be combined much more easily (Java basically uses the union of all methods)

like image 80
Christopher Oezbek Avatar answered Nov 02 '22 09:11

Christopher Oezbek