Pages

Wednesday, April 2, 2014

How would you decide if a class should be abstract class or interface?

It depends :)

In my opinion, to implement methods in abstract class you need to inherit the abstract class.One of the key benefits of inheritance is to minimise the amount of duplicate code by implement common functionalities in parent classes. so if the abstract class have some common generic behaviour that can be shared with its concrete classes, then using abstract class would be optimal.

However, if all methods are abstract and those methods do not represent any unique/significant behaviour related to  the class instances, it may be better to use interface instead.

Use abstract classes to define planned inheritance hierarchies. Classes with already defined inheritance hierarchy can extend their behavior in terms of the “roles” they can play, which are not common to its parents all the other children, using interfaces. Abstract classes will not help in this situation because of multiple inheritance restriction in  java language.

No comments:

Post a Comment