Suppose I have requirement where I have Shape which contains area as only operation. So should I go for interface or abstract class with area() as abstract method ? Reason behind asking this question is : In pure object oriented term all the behavior maps to method and attribute maps to data member. So area is behavior or (calculated) attribute of class ? And which one is better for particular use case ? Interface with area() as method or Abstract class with area() as abstract method ?
Interface or abstract class. Which suits better in my use case?
1.1k Views Asked by Silent Warrior At
3
There are 3 best solutions below
0

Because java doesnt support multipe inheritence you are better with an interface in this case as then you ar not tied down so much. You do not describe any other common behavours or attributes that this type of object must share which would have strenghtned the case for an abstract class. For example if you have another shared method common to all shapes that uses the outpiut of area, that woukd be a case to use an abstract class. Hope this helps
Interfaces
are used when there is generic methods that must be implemented to fullfil the interface contract.Abstract
classes are used when there is some partial default behavior of an implementation of anInterface
that can be shared amongst a majority of the extending classes. Usually anAbstract
classimplements
someInterface
and provide a partial default behavior to some of the methods.So I would have a Shape
Interface
with thearea()
method since the implementation area of the shape to be calculated will vary it doesn't make sense to have anAbstract
class.Example: Circles, Triangles and Rectangles have completely different formulas for calculating area. An
Abstract
implementation of aFourSidedPolygon
class might be appropriate forSquare
andRectangle
classes to inherit from, this is probably a waste of effort since they are just a specialization of a genericPolygon
class which would be more appropriate for non-circle objects.