7. 자바(JAVA) - 객체 자신을 가리키는 this

병호·2023년 7월 9일

자바

목록 보기
7/24

this가 하는 일

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

2. 생성자에서 또 다른 생성자를 호출 할 때 사용

3. 자신의 주소(참조값)을 반환 함

생성된 인스턴스 메모리의 주소를 가짐

클래스 내에서 참조변수가 가지는 주소 값과 동일 한 주소 값을 가지는 키워드

public void setYear(int year)
{
    this.year = year; //this.year의 year는 멤버변수, year는 메소드 setYear의 매개변수임
}

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

1. 클래스에 생성자가 여러개인 경우, this를 이용하여 생성자에 다른 생성자를 호출할 수 있음

2. 생성자에서 다른 생성자를 호출하는 경우, 인스턴스의 생성이 완전하지 않은 상태이므로 this() statement 이전에 다른 statement를 쓸 수 없음

public class Person {

	String name;
	int age;
	
	public Person() {
		this("이름없음", 1); //매개변수가 2개인 Person 생성자 호출
	}
	
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
}

자신의 주소를 반환하는 this

public class Person {

	String name;
	int age;
	
	public Person() {
		this("이름없음", 1);
	}
	
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	public Person getPerson() {
		return this; // 자신의 주소를 반환하는 this
	}
	
	
	public static void main(String[] args)
	{
		Person p = new Person();
		p.name = "James";
		p.age = 37;
		
		Person p2 = p.getPerson();
		System.out.println(p);
		System.out.println(p2);
	}
}

profile
안녕하세요

0개의 댓글