Time t = new Time(); // 기본 생성자
t.hour = 12;
t.minute = 34;
t.second = 56;
Time t = new Time(12,34,56); // 매개변수 있는 생성자 호출, 생성자 쓰는 이유
class Data1 {
int value;
// 컴파일러가 기본 생성자 자동 추가
// Data1() {}
}
class Data2 {
int value;
// 생성자가 하나도 없을 때만 컴파일러가 기본 생성자 자동 추가
// 생성자가 하나라도 있으니까 기본 생성자 따로 추가해줘야 함
// Data2() {}
Data2(int x) {
value = x;
}
}
public class c6_6_210413 {
public static void main(String[] args) {
Data1 d1 = new Data1();
Data2 d2 = new Data2(); // ERROR:Data2(){} 기본 생성자 없으면
}
}
class Car2 {
String color; // this.color
String gearType; // this.gearType
int door; // this.door
// 코드 중복 제거하기 위해 this 사용
Car2(){
color="white";
gearType="auto";
door=4;
}
Car2() {
this("white", "auto", 4);
// 첫 줄
// Car2(String c, String g, int d) 호출
}
Car2(String color) {
this(color, "auto", 4);
// 첫 줄
// Car2(String c, String g, int d) 호출
}
Car2(String c, String g, int d) {
this.color = c;
this.gearType = g;
this.door = d;
}
}
this("white", "auto", 4);
// lv와 iv의 이름이 똑같으므로 this 생략 불가
Car2(String color, String gearType, int door) { // lv
this.color = color; // iv = lv
this.gearType = gearType;
this.door = door;
}
Car2(String c, String g, int d) { // lv
this color = c; // iv = lv
gearType = g; // this 생략 가능
door = d;
}
static long add(long a, long b) {
return a + b; // 객체 생성 여부 모르기 때문에 iv 사용 불가하여 this도 사용 불가
this
this(), this(매개변수)
생성자로써 같은 클래스의 다른 생성자를 호출할 때 사용한다.