Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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

Abstract Classes are used when you want to maintain a hierarchy and interfaces are used when you give a generic layer of abstraction to set of classes. If you want to use this class in a logical hierarchy then you should write Abstract class for Shape. Which will be more suitable in your case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top