생성자는 말 그대로 객체를 생성하는 역할을 하는 클래스의 구성 요소로서 인스턴스가 생성될 때 호출되는 인스턴스 초기화 메서드이다. 하지만 메서드와는 다른점이 있는데 첫 번째는 생성자의 이름이 반드시 클래스의 이름과 같아야 한다는 점, 두 번째는 생성자는 리턴 타입이 없다는 점이다.
클래스명(매개변수) { // 매개변수가 없을 수도 있다.
...
}
public class Constructor {
public Constructor() { ... } // 생성자
}
public class Constructor {
public Constructor() { ... }
// 매개변수가 없는 생성자
public Constructor(int a, String b) { ...}
// 2개의 매개변수를 가진 생성자
Constructor ex1 = new Constructor(5, "abc");
// 생성자 Constructor(int a, String b) 호출
Constructor ex2 = new Constructor();
// 생성자 Constructor() 호출
new키워드를 통해 객체를 생성할 때 한번만 호출된다.public void Constructor() { ... }
// 오류
this와 this()자바에서 'this'와 'this()'의 차이점은 'this' 키워드는 인스턴스 자신을 가르키고, 'this()' 키워드는 생성자를 뜻한다.
class car {
String color;
String gearType;
int door;
Car(String color, String gearType, int door) {
this.color = color;
this.gearType = gearType;
this.door = door;
}
}
- 'this'는 생성자의 매개변수로 선언된 변수의 이름이 인스턴스 변수와 같을 때 인스턴스 변수와 지역변수를 구분하기 위해 사용한다.
- 생성자 안에서의 this.color는 인스턴스 변수, color는 매개변수로 정의된 지역변수이다.
- static 메서드에서는 this를 사용할 수 없다.
class Car {
String color;
String gearType;
int door;
Car() {
this("white", "auto", 4);
// Car(String color, String gearType, int door)
}
Car(String color) {
this(color, "auto", 4);
}
Car(String color, String gearType, int door) {
this.color = color;
this.gearType = gearType;
this.door = door;
}
}
this()는 같은 클래스의 다른 생성자를 호출할 때 사용한다.
Car()생성자와Car(String color)생성자는this()를 통해 모두Car(String color, String gearType, int door)생성자를 호출하고 있다.