본문 바로가기

JAVA/#혼공단3기

[혼공자] 2주차 - 상속(기본미션)

이번주 혼공단 3기 기본미션 과제는 상속된 클래스를 실행시 부모클래스와 자식클래스의 생성자 호출 순서를 확인하는 과제이다.

예제코드와 결과 화면을 먼저 보자.

부모 클래스 소스:

package sec01.verify.exam05;

public class Parent {
    public String nation;

    public Parent() {
        this("대한민국");
        System.out.println("Parent() call");
    }

    public Parent(String nation) {
        this.nation = nation;
        System.out.println("Parent(String nation) call");
    }
}

자식 클래스 소스:

package sec01.verify.exam05;

public class Child extends Parent {
    private String name;

    public Child() {
        this("홍길동");
        System.out.println("Child() call");
    }

    public Child(String name) {
        this.name = name;
        System.out.println("Child(String name) call");
    }
}

TEST 소스:

package sec01.verify.exam05;

public class ChildExample {

    public static void main(String[] args) {

        Child child = new Child();

    }

}

실행결과:

Parent(String nation) call
Parent() call
Child(String name) call
Child() call

자식 객체를 생성하면 부모 객체(Parent)가 먼저 생성되고 다음에 자식 객체(Child)가 생성된다.

Child 객체를 생성하면 부모 객체인 Parent 객체가 생성되면서 부모 생성자가 호출되고, 다음으로 자식 생성자가 호출된다. 그림을 통해 실행 순서의 순번을 표시했다.

1번 Parent() 기본생성자가 제일 먼저 실행되는데 이때 생성자내 this("대한민국")을 통해 2번째 Parent(String nation) 생성자를 실행시킨다. Parent(String nation) 생성자가 종료전 "Parent(String nation) call"을 출력하고 기본생성자 내 "Parent() call"을 출력하고 종료된다.

자식 클래스(Children)에서도 동일하게 기본생성자가 먼저 호출되지만 this("홍길동")으로 4번째 Child(String name)생성자를 실행시킨다. 그리고 4번째 생성자가 종료전에 "Child(String name) call"을 화면에 출력하고 마지막으로 세번째 Child 기본생성자의 "Child() call"을 화면에 출력한다.

그래서 최종 화면에 출력되는 결과는 아래와 같다.

Parent(String nation) call
Parent() call
Child(String name) call
Child() call

이것으로 2주차 미션을 완료한다.