Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use an interface instead of an abstract class and vice versa?

This may be a generic OOP question. I wanted to do a generic comparison between an interface and an abstract class on the basis of their usage.

When would one want to use an interface and when would one want to use an abstract class?

like image 706
Chirantan Avatar asked Jan 26 '09 08:01

Chirantan


People also ask

When we should use interface instead of abstract class?

If you are creating functionality that will be useful across a wide range of objects, then you must use an interface. Abstract classes, at the end of the day, should be used for objects that are closely related. But the interfaces are best suited for providing common functionality to unrelated cases.

In which of these situations are interfaces better than abstract classes?

An interface is better than a abstract class when you want multiple classes to implement that interface and when you don't have to inherit default behavior.

Why do we prefer interface over abstract class?

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.


2 Answers

I wrote an article about that:

Abstract classes and interfaces

Summarizing:

When we talk about abstract classes we are defining characteristics of an object type; specifying what an object is.

When we talk about an interface and define capabilities that we promise to provide, we are talking about establishing a contract about what the object can do.

like image 116
Jorge Córdoba Avatar answered Oct 07 '22 13:10

Jorge Córdoba


An abstract class can have shared state or functionality. An interface is only a promise to provide the state or functionality. A good abstract class will reduce the amount of code that has to be rewritten because it's functionality or state can be shared. The interface has no defined information to be shared

like image 20
Alex Avatar answered Oct 07 '22 13:10

Alex