클래스와 객체_5

김민아·2025년 1월 14일

Java

목록 보기
13/14

this에 대해 자세히 알아보자

  • this 가 하는 일

자신의 인스턴스의 메모리를 가리킴

생성자에서 다른 생성자를 호출함

자신의 주소를 반환함

*참고로 이클립스에서 멤버변수는 다 파란색으로 표시 됨

-자신의 인스턴스의 메모리를 가리키는 this

class Birthday{
    int day;   //멤버변수
    int month;
    int year;
  
    public void setYear(int year){
        this.year = year;     //여기서 this를 써야하는 이유 : this를 써야 멤버변수 year로 인식함
    }
    public void printThis() {
        System.out.println(this);    
    }
}

주의할 점은 this.year 이 아니라 그냥 year로 쓰게 되면 파라미터 year로 인식된다.

  • 생성자에서 다른 생성자를 호출하는 this

객체가 생성될 때 초기화 작업( 멤버변수 셋팅) 할 때 생성자에서 다른 생성자를 호출 할 때 this를 쓸 수 있다.

*여기서 생성자는 public Persin() {}

class Person{
    String name;
    int age;

    public Person() {
        this("이름없음", 1);   //초기화
    }

    public Person(String name, int age) {
        this.name = name; 
        this.age = age;
    }
}

public class CallAnotherConst {
    public static void main(String[] args) {
        Person p1 = new Person();
        System.out.println(p1.name);
    }
}

예를들어 p1에 name = "이름없음", age = 1 이라는 기본값 넣고싶음.

이때 Person() 생성자에서 Person(String name, int age) 생성자를 this로 호출하여 초기화를 한다는 뜻이다.

this쓰고 맞는 인자값을 괄호에 넣는다면 알아서 맞는 생성자와 매핑 시켜준다.

주의할 점은 "생성자에서 생성자를 호출하는 this"를 쓸 때는 생성자와 this사이에 다른 코드를 넣을 수 없다.

(Person() 생성자에서 다른 생성자를 호출 했을때 호출 한 생성자를 돌고 나서 Person() 생성자의 인스턴스가 생성되는데 다른 초기화가 이루어져 에러 발생할 수 있기 때문에 인듯 )

_ 자신의 주소를 반환하는 this

class Person{
    String name;
    int age;

    public Person() {
        this("이름없음", 1);   //초기화
    }

    public Person(String name, int age) {
        this.name = name; 
        this.age = age;
    }

    public Person returnSelf() {
        return this;
    }
}
public (자신 클래스명) (메소드 이름)() {

        return this;

    }

이렇게 하면 된다.
[출처] 13. 클래스와 객체_5|작성자 콩꼼

profile
천천이 꾸준히

0개의 댓글