2014년 3월 11일 화요일

Java - 자기자신을 참조하는 this

## this 키워드
◈ 자기 자신을 직접 참조할 수 있는 참조변수이다.
◈ 클래스 내에서 자신의 멤버들을 직접 참조할 수 있다.
◈ 클래스 내에서 자기 자신을 참조할 수 있는 유일한 키워드이다.

## this 를 이용한 멤버의 접근
◈ this.멤버변수
◈ this.멤버메서드

### this ###
public class SoloThis {
    private int i = 0;
 
    public SoloThis getMySelf() {
        //this 자체를 리턴, this의 형은 클래스의 형
        return this;
    }
    public void print(int i){
        // this 가 없을경우 지역변수 print(int i)를 할당하여 결과 값이 0
        // this 를 명시적으로 넣어주었을때 멤버 변수를 할당하여 1,2,3,4 증가 값이 나옴
        this.i++;
        System.out.println("member i = " + this.i);
    }
    public static void main(String args[]) {
        SoloThis st1 = new SoloThis(); //객체생성
        System.out.println("SoloThis st1:" + st1);
        st1.print(1);
        st1.print(1);
        SoloThis st2 = st1.getMySelf(); //객체 생성
        System.out.println("SoloThis st2:" + st2);
        st2.print(1);
        st2.print(1);
    }
}


### this() ###
# 클래스의 객체를 생성했을 때 자동으로 생성자가 호출.

이렇게 생성자 내에서 또 다른 생성자를 호출하는 것이 가능합니다. 하지만 생성자를 호출할 때는 두 가지 정도의 규칙을 지켜야 합니다.

▣ this를 이용해서 생성자를 호출할 때의 규칙
◈ 반드시 생성자 내에서 다른 생성자를 호출해야 한다.
◈ 생성자에서 this를 이용한 생성자 호출은 어떠한 작업보다도 먼저 선행되어야 한다.
◈ 즉 this를 이용한 생성자 호출 앞에는 어떠한 구문도 사용할 수 없다.

생성자는 마음대로 호출할 수 있는 메서드가 아닙니다. 객체의 메모리가 생성될 때 new와 함께 호출되는 것이 생성자입니다. 예외적인 방법으로 생성자를 호출할 수 있는 방법을 this가 제공하고 있는 것입니다.

▣ this의 세 번째 기능
◈ this를 이용해서 생성자 내에서 다른 생성자를 호출할 수 있다.
◈ 생성자를 재사용할 수 있다.
◈ 생성자에서 다른 생성자를 호출할 때 생성자 호출은 제일 윗부분에 사용해야 한다.


public class CallingThis {
    private String name;
    private int age;
    public CallingThis(){
        this("이름없음");
        //this를 이용해서 CallingThis(String name)생성자 호출
        System.out.println("CallingThis() 생성자 완료");
    }
    public CallingThis(String name) {
        this(name, 12);
        //this를 이용해서 CallingThis(String name, int age) 생성자 호출
        System.out.println("CallingThis(String name) 생성자 완료");
    }
    public CallingThis(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println("name:" + this.name + "  number:" + this.age);
        System.out.println("CallingThis(String name, int age) 생성자 완료");
    }
    public static void main(String[] args) {
        CallingThis c = new CallingThis();
    }
}

댓글 없음:

댓글 쓰기