1. Introduction
Java 프로그래밍을 배우기 시작하면 다양한 키워드를 접하게 됩니다. 그 중 “this”는 클래스와 객체지향 개념을 이해하는 데 매우 중요한 역할을 합니다. 하지만 “this”라는 단어가 영어로는 단순히 “이것/이것을”이라는 의미이기 때문에, 초보자들은 처음에 프로그래밍에서 왜 사용되는지 혼란스러워합니다.
이 글에서는 Java에서 “this” 키워드의 역할과 사용법을 명확하고 초보자 친화적으로 설명합니다. 멤버 변수와 지역 변수를 구분하는 방법, 생성자 안에서 “this”를 사용하는 방법 등을 실용적인 코드 예제와 함께 배울 수 있습니다.
또한 흔히 묻는 질문, 실수하기 쉬운 부분, 중요한 주의사항도 다룹니다. 이 가이드를 끝까지 읽으면 this 키워드가 어떻게 동작하는지, 기본부터 고급 상황까지 자신 있게 활용하는 방법을 이해하게 될 것입니다.
2. What Is the “this” Keyword?
Java에서 “this”는 현재 객체 자체를 가리킵니다. 클래스에서 인스턴스(객체)를 생성하면, 그 특정 객체를 가리키기 위해 “this” 키워드를 사용합니다.
같은 클래스에서 여러 객체를 만들더라도 각 객체의 this는 서로 다른 인스턴스를 가리키므로, 코드 안에서 “현재 어떤 객체가 동작하고 있는가”를 명확히 할 수 있습니다.
The Basic Roles of this
- 인스턴스 변수와 메서드에 접근
this.variableName혹은this.methodName()을 사용하면 해당 객체의 변수와 메서드에 접근할 수 있습니다. - 지역 변수와 인스턴스 변수를 구분 생성자 매개변수나 메서드 매개변수가 멤버 변수와 이름이 동일할 때, “this”를 사용해 둘을 구분합니다.
Why do we need “this”?
Java에서는 하나의 클래스에서 여러 객체를 만들 수 있으며, 각 객체는 독립적인 상태와 동작을 가집니다. 이러한 객체들 안에서 “이 객체 자체”를 가리키는 방법이 필요합니다.
바로 “this” 키워드가 그 역할을 합니다. 예를 들어 Person 클래스 안에서 “this”를 사용하면 “이 특정 Person 객체”를 표현할 수 있습니다.
Summary
“this”는 객체지향 프로그래밍에서 매우 중요한 개념입니다. 객체가 자신의 데이터와 동작에 접근할 수 있게 해 주는 다리 역할을 합니다.
3. Main Use Cases of this
“this” 키워드는 Java 곳곳에서 등장합니다. 아래는 대표적인 예시와 코드 샘플을 모아 놓았습니다.
3.1 Distinguishing Member Variables From Local Variables
Java에서는 생성자 매개변수와 멤버 변수가 같은 이름을 가질 때가 많습니다. 이 경우 “this”를 사용해 두 변수를 구분합니다.
예시: 멤버 변수와 지역 변수를 구분하기
public class Student {
private String name;
public Student(String name) {
this.name = name; // Left: member variable, Right: constructor parameter
}
}
this를 생략하면 지역 변수가 우선 적용되어 멤버 변수에 올바르게 할당되지 않습니다.
3.2 Using this in Constructors
Java는 생성자 오버로딩을 통해 여러 개의 생성자를 정의할 수 있습니다. this()를 호출하면 다른 생성자를 재사용해 중복 코드를 줄일 수 있습니다.
예시: this()를 이용해 다른 생성자 호출하기
public class Book {
private String title;
private int price;
public Book(String title) {
this(title, 0); // calls another constructor
}
public Book(String title, int price) {
this.title = title;
this.price = price;
}
}
이렇게 하면 초기화 로직을 한 곳에 모아 중복을 방지할 수 있습니다.
3.3 Method Chaining
메서드가 this를 반환하면 같은 인스턴스에 대해 연속적으로 메서드를 호출할 수 있습니다.
예시: 메서드 체이닝
public class Person {
private String name;
private int age;
public Person setName(String name) {
this.name = name;
return this;
}
public Person setAge(int age) {
this.age = age;
return this;
}
}
// Method chaining
Person p = new Person().setName("佐藤").setAge(25);
빌더 패턴이나 설정 클래스 등에서 널리 사용되는 기법입니다.
3.4 현재 인스턴스 전달하기
다른 메서드나 클래스에 현재 인스턴스를 전달해야 할 때 “this”를 사용할 수 있습니다.
예시: 현재 객체 전달
public class Printer {
public void print(Person person) {
System.out.println(person);
}
}
public class Person {
public void show(Printer printer) {
printer.print(this); // passes this instance
}
}
4. this 사용 시 중요한 참고 사항
매우 유용하지만, 오류를 방지하기 위해 “this”를 신중하게 사용해야 합니다.
4.1 static 컨텍스트에서는 this를 사용할 수 없음
static 메서드나 변수는 클래스 자체에 속하며 인스턴스에 속하지 않으므로 “this”를 사용할 수 없습니다.
잘못된 예시
public class Example {
private int value;
public static void printValue() {
// System.out.println(this.value); // Compile error
}
}
4.2 this를 과도하게 사용하면 가독성이 떨어질 수 있음
불필요하게 “this”를 사용하면 코드가 읽기 어려워질 수 있습니다. 필요할 때만 사용하세요.
불필요한 사용 예시
public class Test {
private int x;
public void setX(int x) {
this.x = x; // needed
// this.x = this.x + 1; // excessive use
}
}
4.3 this와 super를 혼동하지 마세요
- this → 현재 인스턴스
- super → 상위 클래스(부모 클래스)
예시: this와 super 사용 비교
public class Parent {
public void greet() {
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void greet() {
System.out.println("Child method");
super.greet();
}
}
5. 실용적인 코드 예시
5.1 멤버 변수와 로컬 변수 구분하기
public class Account {
private String owner;
public Account(String owner) {
this.owner = owner;
}
public void printOwner() {
System.out.println("Account Owner: " + this.owner);
}
}

5.2 생성자 체이닝
public class Rectangle {
private int width;
private int height;
public Rectangle(int width) {
this(width, 1);
}
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public void printSize() {
System.out.println("Size: " + width + " x " + height);
}
}
5.3 메서드 체이닝
public class BuilderExample {
private String name;
private int age;
public BuilderExample setName(String name) {
this.name = name;
return this;
}
public BuilderExample setAge(int age) {
this.age = age;
return this;
}
public void printInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
BuilderExample person = new BuilderExample().setName("山田").setAge(30);
person.printInfo();
5.4 현재 인스턴스 전달하기
public class Notifier {
public void notifyUser(User user) {
System.out.println(user.getName() + " has been notified.");
}
}
public class User {
private String name;
public User(String name) { this.name = name; }
public String getName() { return this.name; }
public void sendNotification(Notifier notifier) {
notifier.notifyUser(this);
}
}
Notifier notifier = new Notifier();
User user = new User("佐藤");
user.sendNotification(notifier);
6. 자주 묻는 질문 (FAQ)
Q1. 항상 “this”를 써야 하나요?
A.
항상은 아닙니다. 다음과 같은 경우에 사용하세요:
- 로컬 변수와 멤버 변수 이름이 겹칠 때
- 현재 인스턴스를 명시적으로 참조하고 싶을 때
Q2. static 메서드 안에서 this를 사용하면 어떻게 되나요?
A.
컴파일 오류가 발생합니다. static 메서드는 인스턴스가 아니라 클래스에 속합니다.
Q3. this와 super의 차이점은 무엇인가요?
- this : 현재 인스턴스
- super : 상위 클래스
Q4. 메서드 체이닝에서 this를 반환하는 이점은 무엇인가요?
같은 인스턴스에서 연속적인 호출을 가능하게 하여 가독성을 향상시킵니다.
Q5. 필요할 때 this를 사용하지 않으면 어떻게 되나요?
지역 변수가 멤버 변수를 가릴 수 있어 잘못된 할당 및 버그가 발생할 수 있습니다.
7. 결론
이 문서에서는 Java “this” 키워드를 기본부터 실용적인 사용법까지 설명했습니다. 여러분은 다음을 배웠습니다:
- 멤버 변수와 지역 변수를 구분하는 방법
- 생성자 로직을 중앙 집중화하는 방법
- 메서드 체인을 만드는 방법
- 현재 인스턴스를 다른 메서드에 전달하는 방법
또한 다음과 같은 중요한 주의사항도 다루었습니다:
- “this”는 정적 컨텍스트에서 사용할 수 없습니다
- “this”를 과도하게 사용하지 마세요
- “super”와 함께 올바르게 사용하세요
“this”가 어떻게 작동하는지 이해하면 Java 클래스 설계가 더 명확해지고 버그를 줄일 수 있습니다. Java 기본을 계속 탐구하고 실제 코드에 이 개념들을 적용해 보세요.
