생성자 this()
생성자 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
|
class Refrigerator4 {
int temperature;
int width;
int height;
// 코드의 중복
// Refrigerator4() {
// temperature = 15;
// width = 100;
// height = 150;
// }
Refrigerator4() {
// this() 생성자를 통해 밑의 매개변수 생성자 호출
this(10, 100, 150);
// 첫 줄에서 호출하지 않았으므로 에러 발생
// temperature = 10;
// this(10, 100, 150)
}
Refrigerator4(int temperature, int width, int height) {
this.temperature = temperature;
this.width = width;
this.height = height;
}
}
public class thisExample {
public static void main(String[] args) {
Refrigerator4 R = new Refrigerator4();
System.out.println(R.temperature);
}
}
|
cs |
위 예제를 살펴보겠습니다. 6행부터 11행과 같이 생성자를 사용한다면 22행부터 26행의 생성자와 단순 코드의 중복이 되어버립니다.
따라서 13행부터 15행과 같이 this() 생성자를 통해 코드의 중복을 제거하였고, 17행부터 19행과 같이 첫 줄에 호출하지 않게 되면 에러가
발생합니다.
참조변수 this
괄호가 붙지 않은 this는 참조변수로 사용됩니다. 참조변수 this는 인스턴스 자기 자신을 가리키는 참조변수를 의미합니다.
인스턴스 자기 자신을 가리킨다는 얘기는 곧 인스턴스 메서드와 생성자 내에서 사용 가능하다는 얘기가 됩니다.
매개변수로써 지역 변수(들)를 받게 될 때 인스턴스 변수의 이름과 같게 될 수 있기 때문에 이를 구분해주기 위해 사용됩니다!
1
2
3
4
5
|
Refrigerator(int a, int b, int c) {
temperature = a;
width = b;
height = c;
}
|
cs |
예를 들어 이 예제와 같이 매개변수로써 지역 변수들을 받게 될 때 이 지역변수들의 이름이 인스턴스 변수들의 이름과 같지 않습니다.
따라서 문제 없이 초기화할 수 있습니다.
1
2
3
4
5
|
Refrigerator(int temperature, int width, int height) {
temperature = temperature;
width = width;
height = height;
}
|
cs |
그런데 이번에는 지역 변수들의 이름이 인스턴스 변수들의 이름과 같기 때문에 이를 구별해줄 필요가 있습니다.
1
2
3
4
5
|
Refrigerator(int temperature, int width, int height) {
this.temperature = temperature;
this.width = width;
this.height = height;
}
|
cs |
참조변수 this를 통해 대입 연산자(=)를 기준으로 왼쪽은 인스턴스 변수, 오른쪽은 지역 변수로 명확하게 구별이 가능해졌습니다!
class Refrigerator4 {
int temperature;
int width;
int height;
또한 원래 인스턴스 변수들의 진짜 이름은 this.temperature, this.width, this.height 이고 이 참조변수 this가 생략된 채로 존재하고
있었던 것이었습니다.
'java > 객체지향' 카테고리의 다른 글
11. 상속(Inheritance)과 포함(Composite) (0) | 2023.01.16 |
---|---|
10. 멤버 변수 초기화 및 순서 (2) | 2023.01.16 |
9. 생성자(constructor) (0) | 2023.01.16 |
8. 오버로딩(overloading) (0) | 2023.01.15 |
7. 스태틱 메서드(Static Method), 인스턴스 메서드(Instance Method) (1) | 2023.01.15 |