topic난이도 · 약 15

static과 final

static = 클래스 소유(모든 객체가 공유). final = 변경 불가(변수는 상수, 메서드는 오버라이딩 금지, 클래스는 상속 금지).

#Java#static#final
왜 배우는가

static 변수의 공유 특성이 코드 추적 문제로 자주 나온다. 'static 변수를 바꾸면 모든 객체에 영향을 준다'는 포인트만 잡으면 된다.

java
class Counter {
    static int total = 0;   // 모든 객체가 공유
    int id;

    Counter() {
        total++;
        this.id = total;
    }
}

Counter a = new Counter();
Counter b = new Counter();
Counter c = new Counter();
System.out.println(Counter.total);  // 3
System.out.println(a.id + "," + b.id + "," + c.id); // 1,2,3

final 상수는 보통 `static final`과 함께 쓴다. `public static final int MAX = 100;`

실기 드릴 1문항
code실기 드릴 · 코드 추적

다음 코드의 출력은?

java
class X {
    static int v = 0;
    X() { v++; }
}
public class Test {
    public static void main(String[] args) {
        new X(); new X(); new X();
        System.out.println(X.v);
    }
}