JAVA
Constructor Chaining in java (작성 중)
윤듀2
2023. 5. 15. 00:29
Constructor Chaining(생성자 체이닝)이란
하나의 생성자가 다른 생성자를 호출하는 기술입니다.
중복코드를 피하고 코드가 간소화가 되는 장점이 있습니다.
자바에서 두가지 방법으로 생성자 체이닝을 사용할 수 있습니다.
1. 동일한 클래스 내에서 생성자가 다른 생성자 호출할 때 this() 사용하기
2. 자식 클래스 생성자에서 부모 생성자 호출할 때 super 사용하기
--
public class ConstructorChaining {
public ConstructorChaining(){
this(10);
System.out.println("1");
}
public ConstructorChaining(int a){
this(10,20);
System.out.println("2");
}
public ConstructorChaining(int a, int b){
System.out.println("3");
}
public static void main(String[] args) {
new ConstructorChaining(20);
}
}
참고
https://www.geeksforgeeks.org/constructor-chaining-java-examples/