- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractShapeArea.java
More file actions
Latest commit
73 lines (56 loc) · 1.92 KB
/
Copy pathAbstractShapeArea.java
File metadata and controls
73 lines (56 loc) · 1.92 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
69
70
71
72
73
packageweek03.basic;
importjava.util.ArrayList;
importjava.util.List;
publicclassAbstractShapeArea {
publicstaticvoidmain(String[] args) {
System.out.println("<추상 골격 제공 + 구현 클래스>");
// B-3) 추상 골격 제공 + 구현 클래스
// 문제: `abstract class Shape { abstract double area(); }`를 만들고,
// `Rectangle(w,h)`와 `Circle(r)`이 `area()`를 구현하도록 하라. 리스트에 담아 총 넓이를 구해보라.
// 문제설명: 추상 클래스는 공통 인터페이스(시그니처)를 강제하고, 하위 클래스가 구현 세부를 제공한다.
// 클라이언트는 상위 타입 `Shape`로 묶어 다룰 수 있고, 런타임에는 실제 타입의 `area()`가 호출된다(동적 바인딩).
// 힌트: `abstract class`, `abstract method`, `implements` 아님(클래스 상속), 리스트,
// 향상된 for, 다형성.
Shaper1 = newRectangle(8,7);
Shaper2 = newRectangle(5,2);
Shaper3 = newRectangle(9,3);
Shapec1 = newCircle(4);
Shapec2 = newCircle(6);
List<Shape> list = newArrayList<>();
list.add(r1);
list.add(r2);
list.add(r3);
list.add(c1);
list.add(c2);
doublesum = 0.0;
for (Shapes : list) {
sum += s.area();
}
System.out.println("총 넓이: " + sum);
}
}
abstractclassShape { // 추상 클래스(추상 메서드가 있으면 그 구현을 하위 클래스에 강제한다)
abstractdoublearea();
}
classRectangleextendsShape {
privatedoublewidth;
privatedoubleheight;
Rectangle(doublewidth, doubleheight) { //생성자
this.width = width;
this.height = height;
}
@Override
doublearea() { // 추상 메서드
returnwidth * height;
}
}
classCircleextendsShape {
privatedoubler;
Circle(doubler) { //생성자
this.r = r;
}
@Override
doublearea() { // 추상 메서드
returnr * r * Math.PI;
}
}