다음 Java 프로그램에서 두 객체가 공유하는 필드와 각 객체가 따로 보관하는 필드의 변화를 추적하여 출력 결과를 줄 단위로 쓰시오.
class Counter {
static int shared = 4;
int local;
Counter(int seed) {
local = seed;
shared += seed;
}
int next() {
local += 2;
return ++shared + local;
}
}
public class Main {
public static void main(String[] args) {
Counter first = new Counter(3);
Counter second = new Counter(1);
System.out.println(first.next());
System.out.println(second.next());
System.out.print(Counter.shared + ":" + first.local + ":" + second.local);
}
}모범답안
14 13 10:5:3
풀이와 판단 근거
shared는 모든 Counter 객체가 공유한다. 첫 생성 후 7, 둘째 생성 후 8이 된다.
first.next()는 first.local을 5로 만들고 shared를 9로 증가시켜 14를 반환한다. second.next()는 second.local을 3, shared를 10으로 만든 뒤 13을 반환한다.
마지막에는 공유값 10과 객체별 local 값 5, 3이 차례로 출력된다.
자주 틀리는 지점
- 두 객체마다 shared가 별도로 존재한다고 계산함
- 전위 증가된 shared를 덧셈 뒤에 반영한다고 봄
- first.next가 second.local도 함께 변경한다고 오해함
자동 판정 방식
한글·영문 동의어와 문항별 필수 개념을 확인하며, 정답 단어가 부정되거나 반대 개념과 함께 쓰이면 자동 정답으로 확정하지 않습니다. 부분점수는 ITPASSLAB의 학습용 예상 점수입니다.