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 ?
Suppose I have requirement where I have Shape which contains area as only operation.
Share
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.