- Do it! 자바 프로그래밍 입문 온라인 강의를 수강하며 작성하였습니다.
- Section 1. 자바의 핵심 - 객체지향 프로그래밍
- 13강 "클래스와 객체2(1)"
- this가 하는 일
class Birthday{
int day;
int month;
int year;
public void setYear(int year) {
this.year = year;
}
public void printThis() {
System.out.println(this);
}
}
public class ThisExample {
public static void main(String[] args) {
Birthday b1 = new Birthday();
Birthday b2 = new Birthday();
System.out.println(b1);
b1.printThis();
System.out.println(b2);
b2.printThis();
}
}
위 코드는 Birthday 클래스에 printThis()를 통해 this가 자신의 주소를 가리킨다는 것을 확인해보는 코드이다. setYear()에서 this.year에서의 this는 자기 자신의 클래스를 의미하며 this.year은 그 클래스의 year변수를 뜻한다.
b1, b2는 각각 Birthday 객체이다.
b1자체를 출력하고, printThis 메서드를 호출하여 b1에서의 this를 출력해보면 값이 같은 것을 확인할 수 있고, b1과 b2는 heap 메모리에서 다른 메모리 공간을 가지므로 서로 다른 값을 참조하는 것을 확인할 수 있다.
class Person{
String name;
int age;
public Person() {
this("이름없음", 1);
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class CallAnotherConst {
public static void main(String[] args) {
Person p1 = new Person();
System.out.println(p1.name);
}
}
위 코드는 this를 이용하여 다른 생성자(constructor)를 호출하는 예제이다.
p1 변수에 Person 객체를 default 생성자로 호출했고 default 생성자에서는 name과 age를 사용한 생성자를 호출하여 name이 "이름없음"으로 출력된다.
public Person() { int i = 0; this("이름없음", 1); }
위처럼 constructor에서 다른 constructor를 호출할 때에는 그 앞에 다른 코드를 작성할 수 없다.
왜냐하면 constructor 안에서 다른 constructor를 호출하면 내부의 constructor가 호출되어야 초기화가 이루어지는데, 그 전에 다른 코드가 작성되어 초기화를 시도하면 오류를 발생시킬 수 있기 때문이다.