24-1아래 Java 프로그램을 실행했을 때 출력되는 값을 적으시오.c… | 2024년 정보처리기사실기 1회차 기출문제 상세 페이지
17
24-1
아래 Java 프로그램을 실행했을 때 출력되는 값을 적으시오.
class Ledger {
private static Ledger only = null;
private int total = 0;
private Ledger() {}
static Ledger open() {
if (only == null) {
only = new Ledger();
}
return only;
}
void add(int v) { total += v; }
int total() { return total; }
}
public class Main {
public static void main(String[] args) {
Ledger x = Ledger.open();
x.add(2);
Ledger y = Ledger.open();
y.add(5);
x.add(1);
Ledger z = Ledger.open();
z.add(3);
System.out.print(y.total());
}
}해설
11
[해설]
생성자가 private이고 open()이 처음 한 번만 객체를 만들므로 이 클래스는 싱글톤(Singleton)이다. x, y, z는 모두 같은 객체를 가리킨다.
- x.add(2) → total = 2
- y.add(5) → total = 7
- x.add(1) → total = 8
- z.add(3) → total = 11
어느 참조로 호출하든 하나의 total이 누적되므로 y.total()은 11이다.
내용에 오류가 있거나 최신 법령·기준과 다른 부분이 보이면 알려주세요. 확인 후 반영하겠습니다.