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.2k Views Asked by Silent Warrior At
3
There are 3 best solutions below
0
On
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
Interfacesare used when there is generic methods that must be implemented to fullfil the interface contract.Abstractclasses are used when there is some partial default behavior of an implementation of anInterfacethat can be shared amongst a majority of the extending classes. Usually anAbstractclassimplementssomeInterfaceand provide a partial default behavior to some of the methods.So I would have a Shape
Interfacewith thearea()method since the implementation area of the shape to be calculated will vary it doesn't make sense to have anAbstractclass.Example: Circles, Triangles and Rectangles have completely different formulas for calculating area. An
Abstractimplementation of aFourSidedPolygonclass might be appropriate forSquareandRectangleclasses to inherit from, this is probably a waste of effort since they are just a specialization of a genericPolygonclass which would be more appropriate for non-circle objects.