1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package Mon;
 
import com.sun.xml.internal.ws.api.ha.StickyFeature;
 
import java.util.SplittableRandom;
 
class Car {
    String color; //색상
    String gearType; //변속기종류-auto(자동),manual(수동)
    int door; //문의 개수
 
// ★★★생성자에서 다른 생성자를 호출하는 방법
// 생성자는 다른 생성자를 호출할수가 있으며 그방법은 this를 통해 결정을 한다.
// c1인 참조변수가 Car()라는 인스턴스를 생성하였고, Car()안에는 color,gearType,door 총3개의 변수가 존재하며 초기화가 아직 지정되지는 않았다.
// 인스턴스는 생성자를 무조건 하나만들어야 하기에 아래와 같이 매개변수가 없는 기본생성자가 만들어졌고, Car()라는 생성자는 인스턴스를 초기화를 한후,
//this를 호출한다. 여기서 this란 바로 밑에 존재하는 다른 매개변수가 존재하는 생성자를 호출한다.
//1번생성자에서 white,auto,4라는 숫자가 this를 통해 즉 2번을 호출했기 때문에 전달이 되고 white,auto,4는 color,gearType,door에 대입이 된다.
//그부분이 바로 this.color=color;
//this.gearType=type;
//this.door=door;를 의미한다.
//이후 이것을 확인하기 위해 System.out.pritln을 통해 확인이 가능하다.
 
//다른 방법으로는 인스턴스를 생성할때부터 매개변수의 값을 미리 지정을 하는 것이다.
//c2는 Car()를 참조하고 있으며, 이미 Car()라는 인스턴스에는 blue가 대입이 되어있고 매개 변수가 존재하는 생성자 Car(String color)에 대입이 된다.
//자연스럽게 blue는 color에 대입이 되고, 여기서 this는 다른 생성자인 Car(String color, String gearType, int door)을 호출한다.
//color에 이미 blue가 존재하기에 this(color을 하면 color에는 blue가 존재하고, gearType에는 auto, door에는 4가 대입하게 된다.
//이후 출력을 한다. 확인작업!!
    Car() { //1번 생성자
        this("white""auto"4);//Car(String door, String gearType, int door)를
        //호출
    }
 
    Car(String color, String gearType, int door) {//2번 생성자 이 두번째 생성자가 무조건 있어야 함!!!
        this.color = color;
        this.gearType = gearType;
        this.door = door;
    }
        Car(String color) {
 
        this(color, "auto"4);
    }
}
 
class CatTest2 {
    public static void main(String[] args) {
        Car c1 = new Car();
        Car c2 = new Car("blue");
 
        System.out.println("C1의 color=" + c1.door + ",gearType=" + c1.gearType + ",door=" + c1.door);
        System.out.println("c2의 color=" + c2.color + ",gearType=" + c2.gearType + ",door=" + c2.door);
    }
}
cs

+ Recent posts