본문 바로가기
Java

this(Java)

by 지민재 2022. 7. 12.
반응형
SMALL
this 예약어

 

자바에서 this  인스턴스 자기 자신을 가리키는 키워드이다.

 

  • 인스턴스를 가리키는 변수가 참조변수 이며, 참조변수를 출력하면 '클래스 이름@메모리 주소' 문자열 값이 나옵니다.
  • 출력 결과를 보면 myNum.printThis()메서드를 호출하여 출력한 this 값이 참조 변수 myNum를 출력한 값과 같습니다.
  • 즉, 클래스 코드에서 사용하는 this 생성된 인스턴스 자신을 가리키는 역할을 합니다.
  • this.num3 = num3; 문장으로 참조하면 동적메모리에서 생성된 인스턴스 num3 변수 위치를 가리키고 그 위치에 매개변수 값을 넣어 주는 것입니다.
package study02;

class ThisExample {
	int num1;
	int num2;
	int num3;

	public void setNum(int num3) {
		this.num3 = num3; // myNum.setNum = num3;와 같음
	}

	public void printThis() {
		System.out.println(this); // System.out.println(myNum);와 같음
	}
}

public class thisTest {
	public static void main(String[] args) {
		ThisExample myNum = new ThisExample();
		myNum.setNum(2000);
		System.out.println(myNum);
		myNum.printThis();
	}
}
생성자에서 다른 생성자를 호출하는 this
package study02;

 class ThisEx {
	String name;
	int age;

	ThisEx() {
		this("이름 업음", 1); // this를 사용해 ThisEx(String, int) 생성자 호출
	}

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

public class ThisTest2 {

	public static void main(String[] args) {
		ThisEx noName = new ThisEx();
		ThisEx myName = new ThisEx("민재" , 25);
		System.out.println(noName.name);
		System.out.println(noName.age);
		System.out.println(myName.name);
		System.out.println(myName.age);

	}
}
  • this를 사용하여 생성자를 호출하는 코드 이전에 다른 코드를 넣을 수 없습니다. 만약 다른 코드를 넣으면 오류가 발생합니다.
  • 생성자는 클래스가 생성될 때 호출되므로 클래스 생성이 완료되지 않은 시점에 다른 코드가 있다면 오류가 발생할 수 있습니다.
  • 즉, 디폴드 생성자에서 생성이 완료되는 것이 아니라 this를 사용해 다른 생성자를 호출하므로 이때는 this를 활용한 문장이 가장 먼저 와야 합니다.

'Java' 카테고리의 다른 글

상속(Java)  (0) 2022.07.18
static 변수 (Java)  (0) 2022.07.13
Java 복습_10  (0) 2022.07.10
Java 복습_09  (0) 2022.07.06
Java 복습_08  (0) 2022.07.04

댓글