this vs this()

YongJun·2023년 8월 30일

JAVA

목록 보기
7/24
post-thumbnail

this

객체 자신을 가리키는 레퍼런스(참조) 변수로, 자신의 객체에 접근할 때 사용됩니다.

  • 주로 멤버변수와 매개변수의 이름이 동일할 때, 이를 구분하기 위해 사용됩니다.

this( )

같은 클래스에서 생성자가 (Overload 된)다른 생성자를 호출할 때 사용됩니다.

  • 주로 코드의 중복을 줄일 목적으로 사용됩니다.
  • this( )는 생성자 코드에서만 사용할 수 있습니다.
  • this( )는 생성자 코드안에서 사용될 때 첫번째 문장으로 다른 코드보다 가장 윗줄에 위치해야 합니다.

예제

1) Book 클래스 정의

① this는 객체 자신에 대한 레퍼런스(참조) 변수로, this.price 는 멤버변수 price를 나타냅니다.
② this( )는 생성자안에서 다른 생성자를 호출하므로, this(title, 0); 는 매개변수 2개를 가진 생성자를 호출하게 됩니다.

2) Book 객체 생성 및 실행

3) 실행결과

참고

인스턴스 자신의 주소를 반환할 때도 사용한다.

package jun;

class Student{
	private int studentID;
	private String studentName;
	
	public Student(int studentID, String studentName) {
		this.studentID = studentID;
		this.studentName = studentName;
	}
	
	public Student getSelf() {
		return this;
	}
}
public class StudentTest {

	public static void main(String[] args) {
		Student s = new Student(200,"Kwon");
		System.out.println(s);
		
		System.out.println(s.getSelf());
	}

}

/*
jun.Student@5ca881b5
jun.Student@5ca881b5
*/
profile
개(발자어)린이

0개의 댓글