-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericPolygon.java
More file actions
49 lines (41 loc) · 1.38 KB
/
GenericPolygon.java
File metadata and controls
49 lines (41 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// multilevel inheritance; abstract class shape --> abstract class polygon --> class generic polygon
// catches a polygon that doesn't have its own dedicated class (6+ sides).
public class GenericPolygon extends Polygon {
private double sideLength;
private double apothem;
public GenericPolygon(int sides, double sideLength, double apothem) {
super(sides);
this.sideLength = sideLength;
this.apothem = apothem;
}
@Override
public String getName() {
return switch (sides) {
case 6 -> "Hexagon";
case 7 -> "Heptagon";
case 8 -> "Octagon";
default -> "Polygon with " + sides + " sides"; // if the number of sides is more than 8.
};
}
@Override
public double getPerimeter() {
return sides * sideLength;
}
@Override
public double getArea() {
// Area of a regular polygon: (perimeter * apothem) / 2
return 0.5 * getPerimeter() * apothem;
}
@Override
public String toString() {
return String.format(
"%s, sideLength: %.2f, Apothem: %.2f, Sides: %d, Perimeter: %.2f, Area: %.2f]",
getName(),
sideLength,
apothem,
getSides(),
getPerimeter(),
getArea()
);
}
}