public class Main {
public static void main(String[] args) {
new Child();
System.out.println(Parent.total);
}
}
class Parent {
static int total = 0;
int v = 1;
public Parent() {
total += (++v);
show();
}
public void show() {
total += total;
}
}
class Child extends Parent {
int v = 10;
public Child() {
v += 2;
total += v++;
show();
}
@Override
public void show() {
total += total * 2;
}
}
Child 클래스는 Parent를 상속받았고, 생성자에서 show()를 호출하며, 이 show()는 Child 클래스에서 오버라이드된 메서드다.
static int total = 0; ← 클래스 전체에서 공유
int v = 1; ← 인스턴스 변수, 생성 시 초기화됨
생성자:
total += (++v); // v=2 → total += 2 → total = 2
show(); // 오버라이딩된 show() 호출됨 → Child.show()
v += 2; // v = 12
total += v++; // total += 12 → total = 16 → v = 13
show(); // Child의 show() 호출됨
Java는 부모 생성자 → 자식 생성자 순으로 호출되며,
자식 생성자의 필드 초기화는 부모 생성자보다 먼저 수행된다.
단, 자식 필드 초기화는 부모 생성자 호출 전에 이뤄지지만,
오버라이딩된 메서드 호출 시점에는 자식 필드 초기화는 완료되어 있음.
| 단계 | 설명 | total 값 | 기타 |
|---|---|---|---|
| 초기화 | total = 0 | 0 | |
| Parent 생성자 | ++v → 2 | 2 | Parent.v = 2 |
| Child.show() | 2 + 2×2 = 6 | 6 | |
| Child 생성자 | v = 10 → 12, total += 12 | 18 | Child.v = 13 |
| Child.show() | 18 + 18×2 = 54 | 54 |