this의 기본적인 역할this는 현재 생성된 객체 자기 자신을 참조합니다.
객체의 멤버(필드, 메서드)에 접근할 때 주로 사용됩니다.
주요 역할
필드와 지역 변수 구분
public class Person {
String name;
public Person(String name) {
this.name = name; // this를 사용해 필드와 지역 변수를 구분
}
}
현재 객체의 메서드 호출
public void display() {
System.out.println("Hello from " + this.name);
}
this()의 특별한 역할: 생성자 호출this()는 같은 클래스 내의 다른 생성자를 호출하는 특별한 문법입니다.this() 키워드에 부여하여, 생성자 간의 코드 재사용을 가능하게 했습니다.this()로 생성자를 호출하는 이유this()를 사용하면 해당 작업을 중복해서 작성하지 않아도 됩니다.this()를 사용하면 초기화 작업을 하나의 생성자에 집중시킬 수 있어, 코드 유지보수가 쉬워집니다.this()의 사용 규칙같은 클래스 내의 생성자를 호출
this()는 현재 클래스 내의 다른 생성자를 호출할 때만 사용할 수 있습니다. super()를 사용해야 합니다.생성자 내부에서만 사용 가능
this()는 생성자 내부에서만 사용할 수 있으며, 일반 메서드나 다른 곳에서는 사용할 수 없습니다.생성자의 첫 줄에서만 사용 가능
this()는 반드시 생성자의 첫 번째 줄에서 호출되어야 합니다. 예제 1
public class Person {
String name;
int age;
// 기본 생성자
public Person() {
this("Unknown", 0); // 다른 생성자를 호출
}
// 매개변수가 있는 생성자
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
예제 2
class Circle {
// 필드
double radius;
String color;
// 생성자 오버로딩
public Circle() {
this(10.0, "빨강");
// radius = 10.0;
// color = "빨강";
}
public Circle(double radius) {
this(radius, "빨강");
// if (radius <= 0) {
// this.radius = 10.0;
// } else {
// this.radius = radius;
// }
}
public Circle(String color) {
this(10.0, color);
// if (color != null && color.length() > 0) {
// this.color = color;
// } else {
// this.color = "빨강";
// }
}
public Circle(double radius, String color) {
if (radius <= 0) {
this.radius = 10.0;
} else {
this.radius = radius;
}
if (color != null && color.length() > 0) {
this.color = color;
} else {
this.color = "빨강";
}
}
this()와 일반 this의 차이this
this()
예제
public class Person {
String name;
// 기본 생성자
public Person() {
this("Unknown"); // this()로 다른 생성자 호출
}
// 매개변수가 있는 생성자
public Person(String name) {
this.name = name; // this로 필드와 지역 변수 구분
}
}