this : 자기 자신을 나타낸다.
Student s1 = new Student();
라는 인스턴스를 생성시켜서 this 를 사용한다면,
class Person{
String name;
int age;
//1번
public Person() {
this("이름없음 ", 1);
}
//2번
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void showPersononInfo() {
System.out.println(name+","+age);
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p1 = new Person();
p1.showPersononInfo(); // 이름없음, 1
Person p2 = new Person("이매정 ", 10 );
p2.showPersononInfo(); // 이매정, 10
}
}
호출을 위해 사용하는 this()는 항상 첫 문장으로 사용 되어야 한다.
아래와 같은 경우는 에러가 발생한다.
public Person() {
age=10; // 땡 !!!!!!
this("이름없음 ", 1);
}
this : 자기 자신을 가리킨다.
public Person getSelf() {
return this;
}
전체코드
class Person{
String name;
int age;
public Person() {
this("이름없음 ", 1);
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void showPersononInfo() {
System.out.println(name+","+age);
}
public Person getSelf() {
return this;
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p1 = new Person();
p1.showPersononInfo(); // 이름없음, 1
Person p2 = new Person("이매정 ", 10 );
p2.showPersononInfo(); // 이매정, 10
//2번
System.out.println(p2);
//1번
Person p = p2.getSelf();
System.out.println(p);
}
}
this