class Parent {
int x = 100;
Parent() {
this(500);
}
Parent(int x) {
this.x = x;
}
int getX() {
return x;
}
}
class Child extends Parent {
int x = 4000;
Child() {
this(5000);
}
Child(int x) {
this.x = x;
}
}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
System.out.println(obj.getX());
}
}
this()와 super() 호출 흐름 구분Child obj = new Child(); // 자식 생성자 호출
Child() 호출Child() 내부에서 this(5000) → Child(int x) 호출super() 호출 → 부모 Parent() 실행Parent() → 내부에서 this(500) 호출 → Parent(int x) 실행📌 호출 순서 요약
Child() → Child(int) → Parent() → Parent(int)
class Parent { int x = 100; }
class Child extends Parent { int x = 4000; }
Child에도 같은 이름의 x가 선언됨 → 부모의 x는 가려짐getX()는 부모 클래스의 메서드이므로 Parent의 x 참조Parent() → 내부에서 this(500) 호출Parent(int x) { this.x = x; } // Parent의 x = 500
Child() → 내부에서 this(5000) 호출Child(int x) { this.x = x; } // Child의 x = 5000
obj.getX() 호출 시Parent의 getX() → Parent.x 반환 (500)
| 단계 | 코드/위치 | 동작 | Parent.x | Child.x |
|---|---|---|---|---|
| 1 | new Child() | 자식 생성자 호출 | 100 | 4000 |
| 2 | Parent() → this(500) | 부모 필드 설정 | 500 | 4000 |
| 3 | Child() → this(5000) | 자식 필드 설정 | 500 | 5000 |
| 4 | obj.getX() | 부모 메서드 실행 → Parent.x 반환 | 500 | 5000 |
500
이 문제에서 꼭 알아야 할 개념:
super() → 부모 생성자 실행 후 부모 필드 값 변경 (Parent.x = 500)this() → 자식 생성자 실행 후 자식 필드 값 변경 (Child.x = 5000)getX()는 부모 메서드 → Parent.x 사용