본문 바로가기

java 프로그래밍

제 11장 클래스 구성요소/this() 생성자

 

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
클래스의 구성멤버
 
필드, 생성자, 메소드
 
 
 
필드(Field)란?
 
객체의 데이터가 저장되는곳
 
 
 
생성자(Constrcutor)란?
 
객체 생성시 초기화 역활 담당
 
 
 
메소드(Method)란?
 
객체의 동작에 해당하는 실행문
 
 
 
다른 생성자 호출  this()
 
 
 
this()생성자는 자신의 다른 생성자를 호출하는 코드입니다.
 
즉, 자신이 가지고 있는 값을 가져올때 쓰는코드입니다.
 
 
 
예를들면 this.model = model // model 이라는 변수에서 model
 
즉 본인을 불러옵니다.
 
 
 
 
 
Ex)
 
package son;
 
 
 
public class Car {
 
    String model = "Hundai";
 
    int maxSpeed;
 
 
 
    Car(){
 
        
 
    }
 
    
 
    Car(String model){
 
        this(model, 210);
 
    }
 
    
 
    Car(String model,int maxSpeed){
 
        this.model = model;
 
        this.maxSpeed = maxSpeed;
 
    }
 
    
 
    
 
    
 
}
 
 
 
package son;
 
 
 
public class CarE {
 
 
 
    public static void main(String[] args) {
 
    Car c1 = new Car();
 
    
 
    System.out.println("c1.model :" +c1.model);
 
    System.out.println();
 
    
 
    Car c2 = new Car();
 
    System.out.println("c2.model :"+c2.model);
 
    System.out.println("c2.maxSpeed"+c2.maxSpeed);
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    }
 
 
 
}
 
 
 
Colored by Color Scripter
 
cs
출력값 : 
 
 
 
 
 
c2.maxSpeed0
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none; color:white">cs