Constructor (생성자) 어떤분이 물어 봤는데... 대답을 하지 못했다. 지금 까지 왜 constructor를 생성 해줬는지 왜 썻는지 말로 설명 하자니 말이 안나와서 정리하고 공부 하고자 작성합니다.
Constructor은 객체화 시 초기화 해주는 역할을 담당하며 객체에 값을 넣어주기 위해 사용한다.
클래스명 객체명 = new 클래스명();
ex) Person p = new Person();
public class Coffee {
String brand;
int price;
int rating;
//기본 생성자
public Coffee(){}
// 매개변수 생성자
public Coffee(String brand) { // 객체화 시 가장 먼저 사용됨
this.brand = brand;
}
public Coffee(int price, int rating){
this.price = price;
this.rating = rating;
}
}
public class Main(){
public static void main(String[] args) {
Coffee coffee = new Coffee("starbucks");
Coffee starbucks = new Coffee(4500, 4);
}
}