월요일, 12월 23
Shadow

#028 Using this with a Field

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

For example, the Point class was written like this

public class Point {
    public int x = 0;
    public int y = 0;
	
    //constructor
    public Point(int a, int b) {
	x = a;
	y = b;
    }
}

but it could have been written like this:

public class Point {
    public int x = 0;
    public int y = 0;
	
    //constructor
    public Point(int x, int y) {
	this.x = x;
	this.y = y;
    }
}

Each argument to the second constructor shadows one of the object’s fields—inside the constructor x is a local copy of the constructor’s first argument. To refer to the Point field x, the constructor must use this.x.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.