2 분 소요

this

클래스 내부에서 해당 클래스로부터 생성된 인스턴스 자기 자신을 가리키는 this 키워드를 사용할 수 있다. 즉, this는 인스턴스 자기 자신의 메모리 주소를 가진다.

사실 this는 클래스 내부에서 생략해도 되나, 생성자나 메서드의 매개변수 이름과 필드명이 같을 경우에 this를 명시적으로 사용한다.

class MyClass {
	String name;
	int id;
	
	MyClass(String name, int uniqueId) {
		this.name = name;  // #1
		id = uniqueId;
	}
	
	void printInfo() {
		System.out.println("=== 정보 ===");
		System.out.println("이름: " + this.name);
		System.out.println("고유번호: " + id);  // #2
	}
}

public class ThisKeyword {

	public static void main(String[] args) {
		MyClass mc = new MyClass("자바스", 23);
		mc.printInfo();
	}

}

예제 1-1

=== 정보 ===
이름: 자바스
고유번호: 23

예제 1-1 실행결과

위 예제에서, MyClass 클래스 내부의 생성자 메서드에서, 매개변수인 name과 필드명 name이 겹치기에 이를 구분하기 위해 필드명 앞에 this를 붙인 것을 볼 수 있다. 물론 id 필드명처럼 매개변수명과 겹치지 않을 경우에는 생략해도 문제없다. this는 꼭 생성자 메서드 내부에서만 사용하는 것은 아니고, printInfo() 메서드처럼 인스턴스 메서드 내부에서도 명시할 수 있다.

여기서 this는 MyClass() 객체 자기 자신을 가리키는 참조 변수가 된다.

참고로 이 this는 읽기 전용이다. 이 this 값 자체를 개발자가 변경할 수 없다. (애초에 그럴 필요가 있을까?)

this()

한 편, this 키워드 뒤에 괄호 ()를 붙이는 경우도 있다. this()는 하나의 클래스 내부에서 여러 개의 생성자 메서드들을 오버로딩하여 정의할 때, 특정 생성자 메서드를 다른 생성자 메서드 내부에서 호출할 때 사용한다. 이는 오버로딩한 생성자 메서드들 간의 코드에서 중복되는 점이 있을 때 이 중복을 제거하고자 할 때 사용한다.

주의할 점은, this() 호출은 생성자 메서드의 맨 첫 번째 줄에만 작성할 수 있다는 것이다.

this() 코드 뒤에 추가적으로 원하는 코드를 작성할 수도 있다.

class SiteUser {
	String name;
	int id;
	String phone;
	
	SiteUser(String name) {
		this.name = name;
		this.id = 1;
		this.phone = "000-111-222";
	}
	
	SiteUser(String name, int id) {
		this.name = name;
		this.id = id;
		this.phone = "000-111-222";
	}
	
	SiteUser(String name, int id, String phone) {
		this.name = name;
		this.id = id;
		this.phone = phone;
	}
	
	void printUserInfo() {
		System.out.println("=== 유저 정보 ===");
		System.out.println("이름: " + this.name);
		System.out.println("고유번호: " + this.id);
		System.out.println("전화번호: " + this.phone);
		System.out.println();
	}
}

public class ThisConstructor {

	public static void main(String[] args) {
		SiteUser[] users = {
				new SiteUser("자바스"),
				new SiteUser("김큐엘", 12),
				new SiteUser("정디비", 22, "000-1111-999")
		};
		
		for (SiteUser user : users) {
			user.printUserInfo();
		}
	}

}

예제 2-1

=== 유저 정보 ===
이름: 자바스
고유번호: 1
전화번호: 000-111-222

=== 유저 정보 ===
이름: 김큐엘
고유번호: 12
전화번호: 000-111-222

=== 유저 정보 ===
이름: 정디비
고유번호: 22
전화번호: 000-1111-999

예제 2-1 실행결과

위 예제의 SiteUser 생성자 메서드들을 보면 그 내부에 서로 중복되는 패턴이 있다. 이러한 중복을 줄이기 위해 this()를 사용하여 고쳐보자.

class SiteUser {
	String name;
	int id;
	String phone;
	
	SiteUser(String name) {
		this(name, 1, "000-111-222");
	}
	
	SiteUser(String name, int id) {
		this(name, id, "000-111-222");
	}
	
	SiteUser(String name, int id, String phone) {
		this.name = name;
		this.id = id;
		this.phone = phone;
	}
	
	void printUserInfo() {
		System.out.println("=== 유저 정보 ===");
		System.out.println("이름: " + this.name);
		System.out.println("고유번호: " + this.id);
		System.out.println("전화번호: " + this.phone);
		System.out.println();
	}
}

public class ThisConstructor {

	public static void main(String[] args) {
		SiteUser[] users = {
				new SiteUser("자바스"),
				new SiteUser("김큐엘", 12),
				new SiteUser("정디비", 22, "000-1111-999")
		};
		
		for (SiteUser user : users) {
			user.printUserInfo();
		}
	}

}

예제 2-2

위 예제의 결과는 똑같이 나온다.

생성자 메서드들 중 매개변수가 가장 많은 생성자 메서드를 this()로 호출하도록 고안하였다.

이렇게 this()를 이용하여 오버로딩한 생성자들의 중복되는 코드를 줄일 수 있다.


References

[1] 신용권, “혼자 공부하는 자바”, (한빛미디어, 2024)

This content is licensed under CC BY-NC 4.0

태그: ,

카테고리:

업데이트:

댓글남기기