23-3아래 Java 프로그램을 실행하면 출력되는 문자열을 적으시오.c… | 2023년 정보처리기사실기 3회차 기출문제 상세 페이지
11
23-3
아래 Java 프로그램을 실행하면 출력되는 문자열을 적으시오.
class Machine {
void run() {
System.out.print("P");
stop();
}
void stop() {
System.out.print("Q");
halt();
}
void halt() {
System.out.print("R");
}
}
class Robot extends Machine {
void run() {
super.stop();
System.out.print("S");
this.halt();
}
void halt() {
System.out.print("T");
}
}
public class Main {
public static void main(String[] args) {
Machine m = new Robot();
m.halt();
m.run();
}
}해설
TQTST
[해설]
변수 m의 선언 타입은 Machine이지만 실제 객체는 Robot이므로, 오버라이딩된 메서드는 Robot 쪽이 호출된다.
- m.halt(): Robot.halt() → "T"
- m.run(): Robot.run() 실행 → super.stop()으로 Machine.stop()의 "Q"
- Machine.stop() 안의 halt()도 동적 바인딩으로 Robot.halt() → "T"
- 이어서 "S", this.halt()로 다시 "T"
따라서 출력은 TQTST다. super로 부모 메서드를 불러도, 그 안에서 호출하는 다른 메서드는 여전히 자식의 재정의본이 실행된다.
내용에 오류가 있거나 최신 법령·기준과 다른 부분이 보이면 알려주세요. 확인 후 반영하겠습니다.