Java빈칸 채우기어려움 · 30점#다형성#상속#오버라이딩#예외

89. 타입 검사 후 다운캐스팅과 형 변환 예외

다음 Java 프로그램의 실행 결과가 첫 줄 "27", 둘째 줄 "cast fail 7"이 되도록 빈칸 ①에 들어갈 연산자를 쓰시오.

1class Shape {
2 int size() {
3 return 1;
4 }
5}
6
7class Circle extends Shape {
8 int r;
9
10 Circle(int r) {
11 this.r = r;
12 }
13
14 int size() {
15 return r * r * 3;
16 }
17}
18
19class Rect extends Shape {
20 int w;
21 int h;
22
23 Rect(int w, int h) {
24 this.w = w;
25 this.h = h;
26 }
27
28 int size() {
29 return w * h;
30 }
31
32 int round() {
33 return 2 * (w + h);
34 }
35}
36
37public class Main {
38 public static void main(String[] args) {
39 Shape[] arr = {new Circle(2), new Rect(3, 4), new Shape()};
40 int total = 0;
41 for (Shape s : arr) {
42 if (s ( ① ) Rect) {
43 Rect r = (Rect) s;
44 total += r.round();
45 } else {
46 total += s.size();
47 }
48 }
49 System.out.println(total);
50 try {
51 Rect bad = (Rect) arr[0];
52 System.out.println(bad.w);
53 } catch (ClassCastException e) {
54 System.out.println("cast fail " + total % 10);
55 }
56 }
57}

해설을 먼저 보면 이후 정답 시 점수가 50%만 반영됩니다.