Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a scenario where an Abstract class is preferred over Interface

I am having a scenario where there are several subclasses which have got similar implementations and some extra methods for which the implementations differ with each subclass. I assume that an abstract class would be a good choice for this scenario. But would it be better if that abstract class implements an interface which contains all method declarations.Or should I just stick with the abstract class instead.

In short, I would like to know the scenarios where I should prefer Abstract classes at the top of the hierarchy rather than an Interface.

like image 536
Ebbu Abraham Avatar asked Jun 23 '11 13:06

Ebbu Abraham


3 Answers

Use the abstract class if your subclasses have is-a relationship with the abstract class.

You can have both an abstract class and an interface - the abstract class specifying implementations, and the interface specifying the API.

The collections frameworks is an example of that - it has ArrayList extends AbstractList implements List

like image 138
Bozho Avatar answered Nov 16 '22 06:11

Bozho


An abstract class doesn't have to be completely abstract. You can define certain functions (and variables) that all subclasses will use as-is, and leave only certain methods to be implemented by the subclasses. An interface has the limitation that no functions can be defined.

On the flip side, interfaces allow the flexibility for a class to implement multiple interfaces, whereas a class can only extend one other class. In this sense, an interface will probably always be preferable to a purely abstract class. But there are still plenty of uses for abstract classes which do contain some reused functionality.

like image 21
roberttdev Avatar answered Nov 16 '22 05:11

roberttdev


Abstract class can provide default behaviour where Interfaces cannot. This make sens when a part of the behaviour will be common accross several subclasses.

A very good use of that is the template method pattern : http://en.wikipedia.org/wiki/Template_method_pattern which reduce sequential coupling.

like image 3
deadalnix Avatar answered Nov 16 '22 05:11

deadalnix