This has been boggling me as to why its better to have an abstract class. So lets say i have to calculate areas of a different shapes (circle, rectangle). I was taught its better to have a abstract/interface shape and then classes such as Rectangle, Circle extending it.
I made the following code
abstract class Shape {
abstract int getArea();
}
class Rectangle extends Shape{
private int width;
private int height;
public Rectangle (){
this.width = width;
this.height = height;
}
// get set methods ommited
public int getArea () {
return width * height;
}
}
It seems like shape class serves no purpose. I can't do an impementation of getArea in shape class, since different shapes calculate area differently. I could just remove shape class and make my code simpler.
So what would be the actual purpose of having an abstract/interface class shape? Thanks in advance for any explanations
It seems like shape class serves no purpose. I can't do an impementation of getArea in shape class, since different shapes calculate area differently. I could just remove shape class and make my code simpler.
Suppose you have a picture which is composed of several shapes - some circles, some rectangles etc. You can store all those shapes in a List<Shape>
, and then compute the total area using:
int totalArea = 0;
for (Shape shape : shapes) {
totalArea += shape.getArea();
}
How would you do this if you didn't have a common Shape
class or interface? Your Picture
class would have to know about each individual shape class, rather than using the commonality between the different shape classes to make the code more general.
As another example, consider streams. Imagine that we didn't have the InputStream
class - we just had the individual subclasses. Then every time you wrote code which had to read some data, you'd have to provide an overload for each individual subclass you wanted to be able to handle, even though the code would be exactly the same in each method. InputStream
abstracts away the differences, exposing the common functionality (reading, skipping etc). That way you can write a single method which just takes InputStream
, and then call it with a FileInputStream
, or a ByteArrayInputStream
etc... without the method needing to care which one it receives.
See more on this question at Stackoverflow