문제
다음 Java 코드의 실행 결과를 쓰시오.
Javainterface A { int val = 10; default int getValue() { return val * 2; } } interface B { int val = 20; default int getValue() { return val * 3; } } abstract class Base implements A, B { int val = 30; public int getValue() { return A.super.getValue() + this.val; } abstract void process(); } class Derived extends Base { int val = 40; void process() { System.out.print(val + " "); } public int getValue() { return super.getValue() + B.val; } } public class Main { public static void main(String[] args) { Base b = new Derived(); b.process(); System.out.println(b.val + " " + b.getValue()); } }
정답
40 30 70
40 30 70403070
해설
- b.process() 호출: Derived 클래스의 process() 메서드가 동적 바인딩으로 실행되어 Derived의 val 필드 40 출력
- b.val: 필드는 정적 바인딩되어 Base 클래스의 val 필드 30 출력
- b.getValue() 호출: Derived 클래스의 getValue() 메서드가 동적 바인딩으로 실행
- super.getValue()는 Base의 getValue() 호출: A.super.getValue() + this.val = (10*2) + 30 = 50
- B.val은 인터페이스 B의 상수 20
- 따라서 50 + 20 = 70 반환 최종 출력: '40 30 70'