객체가 생성될 때 호출되며, 객체를 초기화 하는 역할을 한다.
또한, 생성자는 반환 타입이 없고 이름은 클래스 이름과 동일하며, new 연산자에 의해 객체가 생성되며 생성자가 호출된다.
생성자는 객체를 초기화하는 역할을 수행한다.
이전 인스턴스 멤버에서 말했듯 인스턴스들은 각각의 고유한 값을 가지고 있는 데 이 값의 초기값을 세팅해주는 것이 생성자를 호출할 때라고 생각하면 된다.
(만약 각각이 가지는 값이 아닌 동일한 데이터라면 해당 클래스에서 초기값 세팅해주는 것이 좋다.)
public Car(String modelName, String colorName, double priceValue) {
model = modelName;
color = colorName;
price = priceValue;
}//로 생성자를 만들었다면
//Main 클래스
Car car1 = new Car("아우디", "파랑", 100);
Car car2 = new Car("벤츠", "검정", 200);
//과 같이 객체 car1과 car2의 필드값을 초기화하여 인스턴스 별로 고유값을 가지게된다.
이전 메서드 오버로딩에서 나온 개념과 같은 오버로딩이다.
위 포스트에서와 같이 매개변수의 개수, 타입, 순서가 다르면 적용할 수 있으며, 매개변수명만 다를때에는 생성이 안된다.
public Car(String modelName, String colorName, double priceValue)
public Car(String colorName, String modelName, double priceValue)
//이경우 오류가 난다-String String double로 3개의 매개변수, 타입, 순서가 같기 때문
public Car(String modelName, double priceValue)//이렇게 달라야함.
객체, 인스턴스 자신을 표현하는 키워드
String model;
String color;
double price;
public Car(String model, String color, double price) {
//객체 내부 필드와 매개변수명이 같을 때
model = model;
color = color;
price = price;
} //이와 같이 작성된다면 가까운 매개변수를 가리키게 되므로 원하는 대로 작동X
public Car(String model, String color, double price) {
this.model = model;
this.color = color;
this.price = price;
}//이와 같이 작성된다면 해당 객체의 필드에 접근하여 원하는대로 작동O
또한 this는 인스턴스 자신을 뜻하므로 객체의 메서드에서 리턴타입이 자신의 클래스 타입이면 this를 사용하여 자신의 주소를 반환할 수도 있다.
Car returnInstance() {
return this;
}
인스턴스 자신의 생성자를 호출하는 키워드
public Car(String model) {
this(model, "Blue", 500);
}
public Car(String model, String color) {
this(model, color, 100);
}
public Car(String model, String color, double price) {
this.model = model;
this.color = color;
this.price = price;
}
⚠️주의!
this() 키워드를 사용해 다른 생성자를 호출할 때는 반드시 해당 생성자의 첫 줄에 작성되어야한다.public Car(String model) { System.out.println("model = " + model); this(model, "Blue", 50000000); //오류 발생! }