7 kyu
Java: Generic Inheritance
211trashy_incel
Description:
I am creating a class hierarchy of geometrical Shape
s. This is my base class:
abstract class Shape {
public abstract double getArea();
}
And this is a circle:
class Circle extends Shape {
public final double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
There are other shapes, like Rectangle
s, Square
s, etc.
I also wrote an utility class ShapeUtilities
. One of those utilities is a function that computes the total area of a list of shapes:
public static double sumAllAreas(List<Shape> shapes) {
double totalArea = 0.0;
for (Shape shape : shapes)
totalArea += shape.getArea();
return totalArea;
}
This seems to work fine:
List<Shape> shapes = List.of(new Circle(2), new Rectangle(3, 3), new Square(2));
double totalArea = ShapeUtilities.sumAllAreas(shapes); // 25.567
But when I try to call it with a List<Circle>
, the code does not compile, even though Circle
inherits from Shape
:(
List<Circle> circles = List.of(new Circle(2), new Circle(1), new Circle(5));
double totalArea = ShapeUtilities.sumAllAreas(circles); // compilation error !
Can you fix the code so that sumAllAreas()
works with Shape
and all its subtypes ?
Debugging
Language Features
Object-oriented Programming
Similar Kata:
Stats:
Created | Oct 8, 2024 |
Published | Oct 9, 2024 |
Warriors Trained | 435 |
Total Skips | 14 |
Total Code Submissions | 326 |
Total Times Completed | 211 |
Java Completions | 211 |
Total Stars | 5 |
% of votes with a positive feedback rating | 95% of 28 |
Total "Very Satisfied" Votes | 25 |
Total "Somewhat Satisfied" Votes | 3 |
Total "Not Satisfied" Votes | 0 |
Total Rank Assessments | 7 |
Average Assessed Rank | 7 kyu |
Highest Assessed Rank | 6 kyu |
Lowest Assessed Rank | 8 kyu |