-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP47_AbstractClassShapeHierarchy.java
More file actions
68 lines (52 loc) · 1.73 KB
/
Copy pathP47_AbstractClassShapeHierarchy.java
File metadata and controls
68 lines (52 loc) · 1.73 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package programs;
/**
* ============================================================
* PROGRAM 47: Abstract Class Shape Hierarchy
* ============================================================
* Problem: WAP to define an abstract class `GeometryShape`
* with abstract methods `getArea()` and `getPerimeter()`, implemented
* by `SquareGeometry` and `CircleGeometry`.
* ============================================================
*/
abstract class GeometryShape {
protected String color;
public GeometryShape(String color) {
this.color = color;
}
public abstract double getArea();
public abstract double getPerimeter();
public void printStats() {
System.out.printf(" %s Shape -> Area: %.2f | Perimeter: %.2f%n",
color, getArea(), getPerimeter());
}
}
class SquareGeometry extends GeometryShape {
private double side;
public SquareGeometry(String color, double side) {
super(color);
this.side = side;
}
@Override
public double getArea() { return side * side; }
@Override
public double getPerimeter() { return 4 * side; }
}
class CircleGeometry extends GeometryShape {
private double radius;
public CircleGeometry(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
public double getArea() { return Math.PI * radius * radius; }
@Override
public double getPerimeter() { return 2 * Math.PI * radius; }
}
public class P47_AbstractClassShapeHierarchy {
public static void main(String[] args) {
GeometryShape s1 = new SquareGeometry("Blue", 5.0);
GeometryShape s2 = new CircleGeometry("Red", 4.0);
s1.printStats();
s2.printStats();
}
}