매개변수의 이름과 클래스변수와 이름이 같은 경우 혼동을 막기 위해 사용
package ex04;
class Cat {
    // 이름, 색깔
    private String name;
    private String color;
    public String getName() {
        return name;
    }
    public String getColor() {
        return color;
    }
    public Cat(String name, String color) { // 생성자도 statc 생성, 상위 statc 찾기 가능
        this.name = name;  //this는 heap을 가르킴
        this.color = color;
    }
}
public class CatTest {
    public static void main(String[] args) {
        Cat cat = new Cat("츄츄", "하양");
        System.out.println(cat.getName());
        System.out.println(cat.getColor());
    }
}

public Cat(String name, String color) {
        name = name;
    }
위에 코드에서 name(클래스변수) = name(생성자변수)로 표현을 하고 싶은 경우, 이름 똑같아서 JAVA가 어느 name인지 혼동을 한다. 그래서 this라는 함수를 이용한다.
this.name(클래스변수) = name(생성자변수) this를 사용하면 어떤 변수를 가르키는지 JAVA가 알 수 있다.
Share article