this 3가지 사용 방법 - 10
💡 학습 목표
1. 인스턴스(객체) 자신의 메모리를 가리킨다.
2. 생성자에서 또 다른 생성자를 호출할 때 사용할 수 있다.
3. 자신의 주소(참조값, 주소값) 를 반환 시킬 수 있다.
package basic.ch11;
public class Person {
// this의 3가지 사용 방법
// 1. this는 자기 자신을 가리킨다. (인스턴스의 주소)
// 변수 --> private
private String name;
private int age;
private String phone;
private String gender;
// 생성자
public Person(String name, int age) {
// 자기 자신의 멤버 변수 name에 외부에서 들어오는 지역 변수 name을 대입
this.name = name;
this.age = age;
}
public Person(String name, int age, String phone) {
// 생성자에서 다른 생성자를 호출할 수 있다. this(...)
this(name, age);
this.phone = phone;
// 다른 생성자를 가장 먼저 호출하고 다른 수식을 작성해야 한다.
// this.name = name;
// this.age = age;
}
public Person(String name, int age, String phone, String gender) {
this(name, age, phone);
this.gender = gender;
// this.name = name;
// this.age = age;
// this.phone = phone;
}
// 3. 자신의 주소값을 반환 시킬 수 있다.
public Person getPerson() {
// 자신의 주소값을 반환 시킨다.
return this;
}
public void showInfo() {
System.out.println("이름 : " + name + ", 나이 : " + age);
}
public void setName(String name) {
this.name = name;
}
}
package basic.ch11;
public class PersonTest {
// 코드의 시작점
public static void main(String[] args) {
Person person1 = new Person("홍길동", 100);
Person personBox = person1;
Person personBox2 = person1.getPerson();
Person personLee = new Person("이순신", 101);
System.out.println("--------------------------------------------");
// 위 코드까지는 Heap 메모리 영역에 객체가 2개 생성된 상태이다.
// 지역변수인 person1, personBox, personBox2는 같은 객체를 가리킨다.
// 연습 문제 -
// setName 메서드를 만들어 주세요
personBox2.setName("티모");
person1.showInfo();
} // end of main
} // end of class
'Java > Java 객체 지향 핵심' 카테고리의 다른 글
static 변수 - 12 (0) | 2024.04.18 |
---|---|
ver 0.0.1 Starcraft - 11 (0) | 2024.04.18 |
접근 제어 지시자 - 9 (0) | 2024.04.17 |
클래스 설계 자유 실습 (0) | 2024.04.17 |
객체지향 패러다임이란 - 8 (0) | 2024.04.16 |