문제
다음 Java 코드의 실행 결과를 쓰시오.
Javaabstract class Shape { String type = "Shape"; abstract int calculate(); String info() { return type + "-" + calculate(); } } interface Drawable { String type = "Draw"; default String info() { return type + "-Interface"; } } class Circle extends Shape implements Drawable { String type = "Circle"; int calculate() { return 100; } public String info() { return Drawable.super.info() + "-" + super.info(); } } public class Main { public static void main(String[] args) { Drawable d = new Circle(); Shape s = (Shape) d; System.out.println(d.type + " " + s.type + " " + d.info()); } }
정답
Draw Shape Draw-Interface-Shape-100
Draw Shape Draw-Interface-Shape-100DrawShapeDraw-Interface-Shape-100
해설
- d.type: Drawable 인터페이스 타입으로 선언되어 인터페이스 상수 "Draw"를 정적 바인딩
- s.type: Shape 클래스 타입으로 캐스팅되어 Shape의 "Shape" 필드를 정적 바인딩
- d.info(): Circle 클래스의 오버라이딩된 메서드가 동적 바인딩됨
- Drawable.super.info(): 인터페이스의 default 메서드로 "Draw-Interface" 반환
- super.info(): Shape의 info() 메서드 호출, super.type은 "Shape", calculate()는 100이므로 "Shape-100" 반환
- 최종: "Draw-Interface" + "-" + "Shape-100" = "Draw-Interface-Shape-100"