java에서this의 용법 예시 (키워드this)

2592 단어 javathis키워드
this는 그 자체의 은밀한 바늘을 가리킨다. 간단하게 말하면 어떤 대상이this가 있는 방법을 호출하면this는 어떤 대상이다.
예제 코드: TestThis_1.java

/* : this
 * :
 * A@4e44ac6a
 */

public class TestThis_1 {
    public static void main(String[] args) {
        A aa = new A();
        System.out.println(aa.f()); //aa.f(), aa ( )
    }  
}

class A {
    public A f() {
        return this;  // f() A
    }  
}

this의 흔한 용법
1. 같은 이름의 변수 구분
예제 코드: TestThis_2.java

/* this 1:
 * :
 * this. i = 1
 * i = 33
 */
public class TestThis_2 {
    public static void main(String[] args) {
        A aa = new A(33);
    }  
}

class A {
    public int i = 1;                                           // i

    /* : , , */
    public A(int i) {                                           // i
        System.out.printf("this. i = %d
", this.i);            //this.i i
        System.out.printf("i = %d
", i);                       // i i
    }  
}

2. 구조 방법 간의 상호 호출
예제 코드: TestThis_3.java

/* this 2: */
public class TestThis_3 {
    public static void main(String[] args) {

    }  
}

class A {
    int i, j, k;
    public A(int i) {
        this.i = i;
    }  

    public A(int i, int j) {
        /* i = 3;  error   : this(...) ,
         * TestThis_3.java:20: error: call to this must be first statement in constructor
         *      this(i);
         *                  ^
         *                  1 error
         */
        this(i);   
        this.j = j;
    }  

    public A(int i, int j, int k) {
        this(i, j);
        this.k = k;
    }  
}

주의사항
static에 수식되는 방법은this바늘이 없습니다.static에 수식되는 방법은 공공적이기 때문에 어떤 구체적인 대상에 속한다고 말할 수 없다.
예제 코드: TestThis_4.java

/*static this */
public class TestThis_4 {
    public static void main(String[] args) {

    }  
}

class A {
    static A f() {
        return this;
        /* :TestThis_4.java:10: error: non-static variable this cannot be referenced from a static context
         *          return this;
         *                     ^
         *                     1 error
         */
    }  
}

좋은 웹페이지 즐겨찾기