문제
다음 Java 코드의 실행 결과를 쓰시오.
Javaabstract class Shape { String type = "Shape"; abstract int area(); String getType() { return type; } } class Rect extends Shape { String type = "Rect"; int w, h; Rect(int w, int h) { this.w = w; this.h = h; } int area() { return w * h; } String getType() { return type; } } public class Main { public static void main(String[] args) { Shape s = new Rect(3, 4); System.out.println(s.type + " " + s.getType() + " " + s.area()); } }
정답
Shape Rect 12
ShapeRect12
해설
s.type은 선언 타입 Shape의 필드이므로 "Shape". s.getType()은 오버라이딩된 Rect의 메서드가 호출되어 "Rect". s.area()는 Rect의 area()가 호출되어 3×4 = 12. 필드 은닉(hiding)과 메서드 오버라이딩의 차이를 묻는 문제이다.