class Box{
private int l, b, h;
void setDimension(int l, int b, int h) {
l=l;
b=b;
h=h;
}
void display() {
System.out.println(l);
System.out.println(b);
System.out.println(h);
}
}
public class ThisReference {
public static void main(String[] args) {
Box obj= new Box();
obj.setDimension(10, 20, 30);
obj.display();
}
}
코드에서 Box class의 instance 변수 l, b, h가 있고 setDimension()의 지역 변수 l, b, h가 있다.
setDimension()은 instance 변수 l, b, h에 지역 변수들의 값을 할당하려고 하고 있지만 컴파일러는 메서드 내에서 지역 변수에게 우선순위를 부여해 매개 변수들이 매개변수들을 할당하고 있는 상황이 발생한다. main()에서 display()를 호출하더라도 0 0 0이 출력된다.
class Box{
private int l, b, h;
void setDimension(int l, int b, int h) {
this.l=l;
this.b=b;
this.h=h;
}
void display() {
System.out.println(l);
System.out.println(b);
System.out.println(h);
}
}
this
를 사용해 instance 변수와 setDimension()의 매개변수를 구별해준다. this
는 자신의 객체를 참조할 때 사용한다.
메서드 내부에서 사용되는 this
는 메서드가 실행되는, 메서드가 포함된 객체를 참조한다.
public class StaticExample {
static int id;
static String name;
void input(int a, String name1){
id=a;
name=name1;
this.display();
}
private void display(){
System.out.println(id+"\n"+name);
}
public static void main(String[] args) {
StaticExample obj=new StaticExample();
obj.input(2022, "Seong");
}
}
main()에서 input()을 호출하고 input()에서는 this.display()로 자신의 객체에 대한 참조를 하고 있다.