Java - 생성자 호출, this()

왕효준·2023년 6월 9일
0

Java

목록 보기
7/7

생성자를 계속 호출하는 아래 코드를 실행 했을 때, 어떻게 출력이 될까?

Parent 클래스

package Questions.Inhertance.Q7;

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");
    }
}

Child 클래스

package Questions.Inhertance.Q7;

public class Child extends Parent{
    public String name;

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

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

ChildExample 클래스

package Questions.Inhertance.Q7;

public class ChildExample {
    public static void main(String[] args) {
        Child child = new Child();
    }
}

설명

  1. Child() 생성자에서 부모 클래스의 기본 생성자인 Parent() 를 호출한다.
  2. Parent() 생성자에서 this("대한민국")으로 Parent(String nation)을 호출하고, "Parent(String nation) call"을 출력한다.
  3. Parent() 생성자에서 "Parent() call"을 출력한다.
  4. Child() 생성자에서 Child(String name)을 호출한다.
  5. Child(String name) 생성자에서 "Child(String name) call"을 출력한다.
  6. Child() 생성자에서 "Child() call"을 출력한다.

결과

Parent(String nation) call
Parent() call
Child(String name) call
Child() call
profile
자바 백엔드 개발자

0개의 댓글

관련 채용 정보