Java this 키워드

IT/Java 2015. 2. 16. 08:30

자바에서(Java) this 는 '객체, 자기 자신' 을 나타냅니다.

 

주로 3가지 형태로 사용되고 있으며 예를 들어 하나씩 살펴보도록 하겠습니다.

 

 

1. 클래스의 속성과 생성자/메소드의 매개변수(input parameter)의 이름이 같은 경우

- 클래스 속성을 사용할 때 this 키워드를 붙여줍니다

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Fruit {
    public String name;
    public String color;
    public double weight;
    public int count;
        
    public Fruit(String name, String color, double weight, int count) {
        name = name;
        color = color;
        weight = weight;
        count = count;
    }
    
    public static void main(String[] args) {
        Fruit banana = new Fruit("banana""yellow"5.010);
        System.out.println("name : " + banana.name);        // name : null
        System.out.println("color : " + banana.color);      // color : null
        System.out.println("weight : " + banana.weight);    // weight : 0.0
        System.out.println("count : " + banana.count);      // count : 0
    }
}
cs

 

일반적으로 생성자 또는 set / get 메소드의 매개변수(input parameter) 이름은

클래스의 속성 이름과 동일하게 정의되어 사용됩니다.

 

위에서 보여지는 생성자의 매개변수 역시 클래스 속성과 동일한 이름으로 정의되어 있습니다.

그런데 main 메소드에서 Fruit 객체를 생성하고 속성 값들을 출력해 보니 예상치 못한 결과가 나타납니다.

초기화가 이루어지지 않았습니다!! ("banana", "yellow", 5.0, 10 이라고 값을 입력했는데 말이죠!)

 

생성자의 구현부분에서 name = name; 처럼 사용하게 되면

"name 매개변수 = name 매개변수" 형태가 되어 Fruit 객체의 name 속성에는 값이 입력되지 않습니다.

 

안타깝게도 java 는 좌측의 name 이 Fruit 객체의 name 속성을 가리키고 있다는 사실을 인지하지 못합니다.

이럴 때 바로 this 키워드가 사용됩니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Fruit {
    public String name;
    public String color;
    public double weight;
    public int count;
        
    public Fruit(String name, String color, double weight, int count) {
        this.name = name;
        this.color = color;
        this.weight = weight;
        this.count = count;
    }
    
    public static void main(String[] args) {
        Fruit banana = new Fruit("banana""yellow"5.010);
        System.out.println("name : " + banana.name);        // name : banana
        System.out.println("color : " + banana.color);      // color : yellow
        System.out.println("weight : " + banana.weight);    // weight : 5.0
        System.out.println("count : " + banana.count);      // count : 10
    }
}
cs

 

 this.name = name; 은

"Fruit 객체의 name 속성 = name 매개변수" 형태가 되어 Fruit 객체의 속성에 값을 입력하게 됩니다.

 

여기에서의 this 키워드는 객체 자신의 속성을 나타내게 되는 것 입니다.

 

 

2. 클래스에 오버로딩된 다른 생성자 호출 

- 생성자의 최상단(가장 먼저)에 사용되어야 합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Fruit {
    public String name;
    public String color;
    public double weight;
    public int count;
        
    public Fruit(String name, String color) {
        // Fruit(String name, String color, double weight, int count) 를 호출
        this(name, color, 0.00);
    }
    
    public Fruit(String name, String color, double weight, int count) {
        this.name = name;
        this.color = color;
        this.weight = weight;
        this.count = count;
    }
}
cs

 

하나의 클래스에 여러개의 생성자가 오버로딩 되어 있을 때

일부분을 제외하고는 서로 중복된 코드를 가지고 있는 경우가 많이 있습니다.

 

이런 순간에 내부에 정의된 다른 생성자를 호출하여 코드의 중복을 피하고 깔끔한 소스를 작성할 수 있습니다.

같은 클래스에 오버로딩된 다른 생성자를 호출때에도 this 키워드가 사용됩니다.

 

생성자를 호출할 때에는 원하는 생성자의 매개변수를 확인한 후 

메소드를 호출하는 것 처럼 this(매개변수...) 의 형태로 이용하면 됩니다.

 

위에서는 2개의 매개변수를 입력받은 생성자(name, color)의 구현부분에서

4개의 매개변수를 입력받는 생성자(name, color, weight, count) 를 호출하고 있습니다.

 

 

3. 객체 자신의 참조값을 전달하고 싶을 때 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Fruit {
    public String name;
    public String color;
    public double weight;
    public int count;
            
    public Fruit(String name, String color, double weight, int count) {
        this.name = name;
        this.color = color;
        this.weight = weight;
        this.count = count;
    }
 
    public Fruit getFruitInstance() {
        return this;
    }
}
cs

 

어떤 메소드에서는 동작을 완료하고 리턴값으로

어떤 메소드에서는 내부에서 호출하고자 하는 메소드의 매개변수(input parameter) 로 

객체, 자기 자신의 참조값을 전달하고 싶은 경우가 있습니다.

 

이럴때에는 getFruitInstance() 메소드의 구현부분에서처럼 this 키워드를 이용함으로써 구현이 가능합니다.

 

 

자바에서 this 는 자주 사용되는 키워드입니다.

3가지 상황에서처럼 명시적으로 this 를 사용하지 않더라고 "객체, 자기 자신" 을 나타내야 할 때는 묵시적으로

앞부분에 this 가 기입되어 있다고 생각하시면 이해하시기에 더욱 도움이 될 것 같습니다.

 

 

Posted by maze1008
,