JAVA
Setter 대신 Overload 생성자 이용하기
영카이브
2024. 1. 9. 22:40
Setter 메서드
- 장점
- 유연성이 높습니다. 필요한 속성만 설정할 수 있다.
- 일부 속성만 업데이트하고 싶을 때 사용하기 좋다.
- 단점
- 여러 속성을 설정하는 경우 여러 개의 메서드 호출이 필요할 수 있다.
Overloaded 생성자
- 장점
- 한 번의 호출로 여러 속성을 초기화할 수 있다.
- 객체 생성 시 속성이 모두 설정되어야 하는 경우 유용하다.
- 단점
- 유연성이 떨어지고 항상 모든 속성을 설정해야 한다.
일부 속성만 업데이트해야 하는 경우 Setter 메서드가 더 적합하고
객체 생성 시 모든 속성이 필요한 경우 Overloaded 생성자가 더 적합하다.
필요 시 혼용도 가능하다.
Setter 사용
Product product = new Product();
product.setName(name);
product.setPrice(price);
product.setQuantity(quantity);
Overload 생성자 이용
- Overload 생성자를 만들면 기본생성자는 자동생성되지않는다. 생성자가 없을 시에만 자동 생성되므로 따로 만들어준뒤 이를 집중화를 통해 불필요한 중복 코드를 줄인다.
Product product = new Product(name, price, quantity);
public class Product {
String name;
int price;
int quantity;
public Product() {
this("Undefined", 0, 0);
}
public Product(String name, int price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
참고 자료 출처 : https://www.youtube.com/watch?v=edKJbYyUapk