생성자 체이닝이란 무엇입니까?

Java의 생성자는 클래스의 개체 생성에 사용되는 특정 메서드입니다. 생성자는 클래스의 객체가 생성될 때마다 호출됩니다. 생성 시 개체의 속성에 값을 할당하는 데 사용할 수 있습니다. 매개 변수 목록이 다른 Java 클래스에는 여러 생성자가 있을 수 있습니다. 생성자 연결은 객체 생성 시 동일한 클래스/부모 클래스의 생성자의 다른 구현을 호출하는 데 사용됩니다.

생성자 연결은 Java에서 어떻게 구현됩니까?

생성자를 호출하는 방법에 따라 생성자를 연결하는 두 가지 방법이 있습니다. 다음과 같습니다.
  • this() 키워드 사용 – 동일한 클래스의 생성자 호출
  • super() 키워드 사용 – 부모 클래스의 생성자 호출
이것은 다음 예에서 설명됩니다.Java의 생성자 연결 - 1

생성자 연결 예제 #1 – 생성자는 this() 키워드를 사용하여 연결됩니다.

DerivedClass에 대해 4개의 생성자를 선언했습니다. 하나는 인수가 없고 다른 세 개는 다른 인수가 있습니다. 각 생성자 내에서 this() 키워드는 동일한 클래스의 다음 생성자를 호출하는 데 사용됩니다.

package com.tutorialwriting.constchaining;
 
public class DerivedClass{
 
    String firstName;
    String country;
    int age;
 
    public DerivedClass() {
        // calling one argument constructor
        this("Maggie");
    }
 
    public DerivedClass(String firstName) {
        // calling two argument constructor
        this(firstName, 15);
    }
 
    public DerivedClass(String firstName, int age) {
        // calling three argument constructor
        this(firstName, age, "Australia");
    }
 
    public DerivedClass(String firstName, int age, String country) {
        this.firstName = firstName;
        this.age = age;
        this.country = country;
    }
 
    void displayValues() {
        System.out.println("First Name : " + firstName);
        System.out.println("Country : " + country);
        System.out.println("Age : " + age);
    }
 
    public static void main(String args[]) {
        DerivedClass object = new DerivedClass();
        object.displayValues();
    }
}
실행의 출력Java의 생성자 연결 - 2

생성자 연결 예제 #2 – 생성자는 super() 키워드를 사용하여 연결됩니다.

여기서 자식 클래스는 super() 키워드 를 사용하여 부모 클래스의 생성자를 호출합니다 . BaseClass에는 세 개의 생성자가 있습니다. 인수가 없는 생성자는 this() 를 사용하여 BaseClass의 세 인수 생성자 중 하나를 호출합니다 .

package com.tutorialwriting.constchaining;
 
public class BaseClass {
 
    public BaseClass() {
        //calling a three argument constructor of the same class
        this("Male", "English", "1989/11/10");
        System.out.println("I'm executed third!!!");
    }
 
    public BaseClass(String firstName, String surname, int idNo) {
        System.out.println("I'm executed first!");
        System.out.println("First name : " + firstName);
        System.out.println("Surname : " + surname);
        System.out.println("ID Number : " + idNo);
    }
 
    public BaseClass(String gender, String nationality, String birthDate) {
        System.out.println("I'm executed second!!");
        System.out.println("Gender : " + gender);
        System.out.println("Nationality : " + nationality);
        System.out.println("Birth Date : " + birthDate);
    }
 
}
DerivedClass에는 두 개의 생성자가 있으며 각각은 super() 를 사용하여 수퍼 클래스의 다른 생성자를 호출합니다 .

package com.tutorialwriting.constchaining;
 
public class DerivedClass extends BaseClass {
 
    public DerivedClass() {
        //calling no argument constructor of the super class
        super();
    }
 
    public DerivedClass(String firstName, String surname, int idNo) {
        //calling three argument constructor of the super class
        super(firstName, surname, idNo);
    }
 
    public static void main(String args[]) {
        DerivedClass object2 = new DerivedClass("Paul", "Wilson", 123456);
        DerivedClass object1 = new DerivedClass();
    }
}
실행의 출력Java의 생성자 연결 - 3

암시적 대 명시적 생성자 호출

Java에는 암시적 호출과 명시적 호출의 두 가지 생성자 호출 방법이 있습니다.
  • 명시적 호출은 this() 또는 super() 를 사용하여 코드에서 명시적으로 생성자를 호출하는 것을 말합니다 .
  • 암시적 호출은 자식 클래스 생성자로부터의 명시적 호출이 없을 때 암시적으로 슈퍼 클래스의 인수 없는 생성자를 호출하는 것을 말합니다. 즉, 프로그래머 가 명시적으로 코드에서 super()를 호출하지 않는 경우 컴파일러는 자식 클래스 생성자의 첫 번째 줄로 super() 호출을 추가합니다.

생성자 체이닝이 필요한 이유는 무엇입니까?

아래와 같이 Java에서 생성자 체인을 사용하는 목적은 여러 가지가 있습니다.
  • 다른 생성자의 속성이나 부모 클래스의 속성에 접근하는 방법입니다.
  • 다른 생성자를 호출하는 동안 클래스의 현재 인스턴스인 하나의 개체만 사용됩니다. 초기화는 한 곳에서 발생하지만 체인을 통해 다른 생성자 구현을 호출할 수 있는 권한이 있습니다. 이는 메모리 관리 및 코드 유지 관리에 크게 도움이 됩니다.

결론

이 자습서에서는 Java의 생성자 연결에 대해 설명했습니다. 생성자는 객체를 생성하는 동안 호출되는 메서드와 유사한 코드 세그먼트입니다. Java 클래스는 매개변수 목록이 다른 여러 생성자를 가질 수 있습니다. 생성자 연결은 클래스의 한 인스턴스로 다양한 초기화를 처리하는 편리한 방법입니다. 이 자습서에서 주목해야 할 몇 가지 중요한 사항은 다음과 같습니다.
  • 프로그래머가 명시적으로 코드에 추가하지 않으면 컴파일러는 인수가 없는 공용 생성자를 Java 클래스에 추가합니다. 이를 기본 생성자라고 합니다.
  • this()super()는 생성자의 첫 번째 줄로 작성해야 합니다.
  • this() 는 동일한 클래스의 생성자를 호출하는 데 사용되는 반면 super()는 직계 수퍼 클래스의 생성자를 호출하는 데 사용됩니다.
  • 클래스 내에 this() 키워드를 포함하지 않는 생성자가 하나 이상 있어야 합니다.
  • 명시적으로 추가되지 않은 경우 컴파일러는 인수가 없는 super() 호출을 모든 자식 클래스 생성자에 추가합니다. 이렇게 하면 클래스를 올바르게 인스턴스화하는 데 도움이 됩니다.