기본/파라미터 생성자 & 유효성 검사
public class Person{
private final String name;
private final int age;
public Person(String name, int age){
if(name ==null || name.isBlank()){
throw new IllegalArgumentException("name은 필수 입니다.");
}
if(age < 0){
throw new IllegalArgumentException("age는 음수가 될 수 없습니다.");
}
this.name = name;
this.age = age;
}
}
설명 : final 필드를 안전하게 초기화하고, 잘못된 상태 방지. 단점은 유효성 검사 실패 시 생성 자체가 예외로 끝남
오버로딩 + 체이닝 (this())
public class Person{
private final String name;
private final int age;
private final String city;
public Person(String name, int age, String city){
this.name = name;
this.age = age;
this.city = city;
}
public Person(Strign name, int age){
this(name, age,"unknown") //체이닝
}
public Person(String name) {
this(name, 0);
}
}
체이닝
말 그대로 연쇄 연결
생성자끼리 서로 연결해서 호출하는 패턴
목적: 중복 코드 제거 + 초기화 로직 통일
같은 클래스 내 체이닝 → this()
예시
class A{
int x,y;
A(int x, int y){
this.x=x;
this.y=y;
}
A(int x){
this(x,0); // 같은 클래스의 다른 생성자 호출
}
A(){
this(0); //또 다른 생성자 호출
}
}
this() →같은 클래스의 다른 생성자 호출
중복 초기화 코드 방지
호출은 생성자 첫 줄 이어야함
부모 클래스 체이닝 → super()
class Parent{
int a;
Parent(int a) {this.a =a;}
}
class Child extends Parent{
int b;
Child(int a, int b){
super(a); //부모 생성자 호출
this.b = bl
}
}