Java
this를 활용하는 3가지 방법
개발자공부
2024. 4. 18. 22:21
1. 인스턴스(객체) 자신의 메모리를 가리킨다.
☞자기 자신의 멤버 변수 name과 age에 외부에서 들어오는 지역 변수 name, age를 대입.
☞name = name; 이라고 했을 때 작성자는 멤버 변수 = 지역 변수;를 의도하였을지라도 자바는 이해하지 못한다.
public class Person {
private String name;
private int age;
private String phone;
private String gender;
//첫 번째 방법
public Person(String name, int age){
this.name = name;
this.age = age;
}
}
2. 생성자에서 또 다른 생성자를 호출할 때 사용할 수 있다.
☞생성자는 해당 클래스와 이름이 같아야 한다.
☞public Person(지역 변수){ this.멤버 변수 = 지역 변수 }
☞위에서 이미 사용한 생성자를 부를 수 있다. this(.....)
public class Person {
private String name;
private int age;
private String phone;
private String gender;
//첫 번째 방법
public Person(String name, int age){
this.name = name;
this.age = age;
}
//두 번째 방법
public Person(String name, int age, String phone){
this(name,age);
this.phone = phone;
}
}
3. 자신의 주소(참조값,주소값)를 반환 시킬 수 있다.
public class Person{
private String name;
private int age;
private String phone;
private String gender;
//세 번째 방법
public Person getPerson(){
return this;
}
}