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이 작동하는지 모르겠습니다. 그 순서또한 이해가 안갑니다.

  • 원래 확장 클래스(child)의 생성자는 super()를 한 번 호출하고 시작하는데요. 만약 super() 명시하지 않았으면 컴파일러가 자동으로 추가해주고요. 그런데 이건 좀 흥미롭네요. (왜 이러는지 모르겠다는 말) 편집요청빌런 2020.1.23 01:06

1 답변

    1. Child 인스턴스 생성
    2. Child() 생성자 진입
    3. super 의 Parent() 생성자 진입
    4. Parent() 생성자의 this("..") 로 Parent(Stirng) 생성자 진입
    5. "Parent(String nation) call" 로 Parent(String) 끝
    6. 다시 Parent() 와서 "Parent() call" 로 Parent() 끝
    7. 다시 Child() 와서 this("...") 로 Child(String) 생성자 진입
    8. "Child(String name) call" 로 Child(String) 끝
    9. 다시 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

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)