Java 왜 이런 결과가 나오는지 이해가 안갑니다.
조회수 397회
class Example {
public static void main(String[] args) {
Child child = new Child();
} //main
} // example
class Parent{
String nation;
Parent() {
this("대한민국");
System.out.println("Parent() call");
}
Parent(String nation) {
this.nation = nation;
System.out.println("Parent(String nation) call");
}
} // class parent
class Child extends Parent {
String name;
Child() {
this("홍길동");
System.out.println("Child() call");
}
Child(String name) {
this.name = name;
System.out.println("Child(String name) call");
}
} // class child
이렇게 작성하고 실행하면 main
에서는 그저 child
라는 새로운 객체를 만들었을뿐인데 왜 모든 println
이 작동하는지 모르겠습니다. 그 순서또한 이해가 안갑니다.
-
(•́ ✖ •̀)
알 수 없는 사용자 - 〉
1 답변
-
- Child 인스턴스 생성
- Child() 생성자 진입
- super 의 Parent() 생성자 진입
- Parent() 생성자의 this("..") 로 Parent(Stirng) 생성자 진입
- "Parent(String nation) call" 로 Parent(String) 끝
- 다시 Parent() 와서 "Parent() call" 로 Parent() 끝
- 다시 Child() 와서 this("...") 로 Child(String) 생성자 진입
- "Child(String name) call" 로 Child(String) 끝
- 다시 Child() 와서 "Child() call" 로 Child() 끝
완료
- 현상으로 보면 이게 맞는데, Child()의 첫 줄에 super() 추가 하면 this("홍길동")에서 "생성자 호출은 첫 statement여야 합니다"라며 컴파일 에러 발생합니다. Child(String)의 첫 줄에 super() 추가하면 에러 없구요. 이건 왜 이럴까요? 만약 이 에러 없는 super() 명시가 올바른 방법이라면, 말씀하신 Child() > Parent() > Parent(String) > Child(String) > Child() 순서가 아니라 Child() > Child(String) > Parent() > Parent(String) > Child() 순이 됩니다. 편집요청빌런 2020.1.23 16:34
댓글 입력