인스턴스 초기화 메서드 (=iv 초기화)
생성자의 이름은 클래스 이름과 같아야 한다.
생성자는 리턴값이 없다. (하지만 void를 쓰진 않음)
모든 생성자는 첫 줄에는 반드시 다른 생성자를 호출해야 한다.
그렇지 않으면, 컴파일러가 자동으로 생성자의 첫 줄에 super( );(조상의 기본 생성자)를 삽입
=> 다른생성자 : 같은 클래스의 다른 생성자 / 조상의 생성자
매개변수가 없는 생성자
클래스에 매개변수가 있는 생성자만 존재시, 기본생성자를 호출하면 컴파일러가 자동추가를 해주지 않음.
class Data_2 {
int value;
Data_2() {} // 기본 생성자
Data_2(int x) { // 매개변수가 있는 생성자
value = x;
}
}
class Car {
String color;
String gearType;
int door;
Car() {} //기본 생성자
Car(String c, String g, int d) { //매개변수가 있는 생성자
color = c;
gearType = g;
door = d;
}
}
(같은 클래스내) 생성자에서 다른 생성자를 호출할 때 사용
인스턴스 자신을 가리키는 참조변수 (인스턴스의 주소가 저장됨)
인스턴스매서드(생성자 포함)에서 사용 가능 (예: this.iv
)
iv와 lv를 구분하기 위해서 사용
(생략 가능한데, iv와 lv 이름이 같을 때는 필수)
class Car2 {
String color;
String gearType;
int door;
Car2() {
this("white", "auto", 4); //생성자 this()
}
Car2(String color, String gearType, int door) {
this.color = color; //참조변수 this
this.gearType = gearType;
this.door = door;
}
// iv, lv 구분을 위한 예시
Car2(String c, String g, int d) {
this.color = c; // c, g, d : lv
this.gearType = g; // color, gearType, door : iv
this.door = d;
}
}
조상의 생성자를 호출할 때 사용
public class superTest {
public static void main(String[] args) {
P3D c = new P3D(1,2,3);
System.out.println(c.getLocation());
}
}
class P {
int x;
int y;
P(int x, int y){
this.x = x;
this.y = y;
}
String getLocation() {
return "x:"+x+", y:"+y;
}
}
class P3D extends P{
int z;
P3D(int x, int y, int z){
super(x, y); //조상멤버 초기화를 위해 조상의 생성자 호출
this.z = z;
}
String getLocation() {
return "x:"+x+", y:"+y+", z:"+z;
}
}
💡 컴파일러가 자동 삽입해주는 것
- 기본 생성자 : 클래스 내 생성자가 1개도 없을 경우
- super( ) : 생성자 첫 줄에 생성자가 없을 경우