"Boldness has genius, power, and magic in it." - Johann Wolfgang von Goethe

JAVA_SPRING

[JAVA] 객체 자신을 가리키는 this 개념 및 사용법

Toproot 2022. 9. 26. 22:04
728x90
728x90

image

학습내용

  • this의 의미와 사용 방법 및 주의사항을 알아보자

👈 This의 역할

Java에서 This는 인스턴스 객체 자신의 메모리를 가리킵니다.
C++에서도 사용되는 this는 멤버 변수를 가리킬 때 사용하기도 하지만, 객체를 생성할 때도 사용됩니다.
특히 default Constructor 에서 기존의 생성자를 this를 활용하여 코드를 또 작성하지 않고 생성할 수 있습니다.

생성자에서 또 다른 생성자를 호출할 때 주의사항

생성자는 객체가 생성 될 때 new 키워드를 사용해서 호출됩니다.
this를 활용하면 같은 클래스 내라는 조건 하에 하나의 생성자에서 다른 생성자를 호출할 수 있습니다.
이러한 경우, 인스턴스 생성이 완전하지 않기 때문에 생성자 내의 첫 statement는 꼭 this() statement가 되어야 합니다.

public class Person {

    String name;
    int age;

    // default Construct
    public Person() {
        // 아래 생성된 생성자를 this로 호출.
        // this로 생성자 부를 때는 그 이전에 어떠한 생성도 안됨(최초생성이어야 함)
        this("no name", 1);
    }

    public Person(String name, int age) {

        this.name = name;
        this.age = age;
    }
}

생성된 인스턴스 메모리의 주소 공유

this를 활용해서 생성자를 호출하여 객체를 생성하게 되면,
클래스 내에서 참조변수가 가지는 주소 값과 동일한 주소값을 가지게 됩니다.
Java 함수의 메모리 개념은 'Stack'과 'Heap' 메모리가 있는데요.
해당 클래스에서 호출된 함수나 메서드의 멤버 변수(지역 변수)는 'Stack' 메모리에 저장되고,
호출하는 값은 'Heap 메모리(변수들이 가리키는 값, 주소)에 저장됩니다.

자신의 주소를 반환하는 this 예제코드

Person

package unit12_this;

public class Person {

    String name;
    int age;

    // default Construct
    public Person() {
        // 아래 생성된 생성자를 this로 호출.
        // this로 생성자 부를 때는 그 이전에 어떠한 생성도 안됨(최초생성이어야 함)
        this("no name", 1);
    }

    public Person(String name, int age) {

        this.name = name;
        this.age = age;
    }

    public void showPerson() {
        System.out.println(name + "," + age);
    }

    public Person getPerson() {
        return this;
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.showPerson();

        System.out.println(person);

        Person person2 = person.getPerson();
        System.out.println(person2);

        // person 과 person2는 같은 생성자를 가리키므로 값이 같다.
        // unit12_this.Person@4fccd51b
        // unit12_this.Person@4fccd51b

    }
}
728x90
728x90