문제
다음 Java 코드의 실행 결과를 쓰시오.
Javainterface A { int value = 10; default String getValue() { return "A:" + value; } } interface B { int value = 20; default String getValue() { return "B:" + value; } } abstract class Base { int value = 30; abstract String process(); } class Child extends Base implements A, B { int value = 40; String getValue() { return "Child:" + A.value; } String process() { return getValue() + "," + super.value; } } public class Main { public static void main(String[] args) { A obj = new Child(); System.out.println(obj.value + " " + obj.getValue() + " " + ((Child)obj).process()); } }
정답
10 Child:10 Child:10,30
10 Child:10 Child:10,3010Child:10Child:10,30
해설
- obj.value: A 타입으로 선언되었으므로 인터페이스 A의 상수 10 출력 (정적 바인딩)
- obj.getValue(): Child에서 오버라이딩된 getValue() 호출. A.value는 인터페이스 A의 상수 10을 명시적 접근하여 "Child:10" 출력 (동적 바인딩)
- ((Child)obj).process(): Child의 process() 호출. getValue()는 Child의 메서드로 "Child:10" 반환, super.value는 Base 클래스의 value 필드 30 접근하여 "Child:10,30" 출력 (동적 바인딩과 super 키워드)