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 ?
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 an Interface
that can be shared amongst a majority of the extending classes. Usually an Abstract
class implements
some Interface
and provide a partial default behavior to some of the methods.
So I would have a Shape Interface
with the area()
method since the implementation area of the shape to be calculated will vary it doesn't make sense to have an Abstract
class.
Example: Circles, Triangles and Rectangles have completely different formulas for calculating area. An Abstract
implementation of a FourSidedPolygon
class might be appropriate for Square
and Rectangle
classes to inherit from, this is probably a waste of effort since they are just a specialization of a generic Polygon
class which would be more appropriate for non-circle objects.