Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 도커 #docker #docker-compose.yml #도커컴포즈 #배포 #spring #mysql #docker-compose
- /
- chatgpt #gpt #챗지피티 #ai
- 도커 #Docker #배포 #Spring #MySQL #백엔드배포
Archives
- Today
- Total
개발자 데뷔!
08. [Java] this 예약어 본문
this
: 생성된 인스턴스 스스로를 가리키는 예약어
this는 크게 다음 세가지 역할로 쓰임을나눌 수 있다.
1. 자신의 메모리를 가리키는 this
2. 생성자에서 다른 생성자를 호출하는 this
3. 자신의 주소를 반환하는 this
보통 1번의 경우로 가장 많이 쓰이지만,
예제와 함께 알아두자.
1. 자신의 메모리를 가리키는 this
클래스 코드에서 사용하는 this는, 생성된 인스턴스 자신을 가리킨다.
ex)
package thisex;
class BirthDay{
int day;
int month;
int year;
public void setYear(int year) {
this.year = year; // bDay.year = year 와 동치
}
public void printThis() {
System.out.println(this); // this = bDay 즉, 클래스 전체를 출력
}
}
public class ThisExmaple {
public static void main(String[] args) {
BirthDay bDay = new BirthDay(); // this가 가리킬 인스턴스가 이부분에서 정해짐
bDay.setYear(2000);
System.out.println(bDay);
bDay.printThis();
}
}
2. 생성자에서 다른 생성자를 호출하는 this
ex)
package thisex;
class Person{
String name;
int age;
// 생성자1
Person(){
this("이름없음", 1); // this를 사용해 Person(String, int)형태인 생성자2 호출
}
// 생성자2
Person(String name, int age){ // 실제 호출되는 생성자2
this.name = name;
this.age = age;
}
}
public class CallAnotherConst {
public static void main(String[] args) {
Person noName = new Person(); // 기본생성자인 생성자1이 먼저 생성되지만, this로 인해
System.out.println(noName.name); // 다시 생성자2를 호출하게됨
System.out.println(noName.age);
}
}
3. 자신의 주소를 반환하는 this
ex)
package thisex;
class Person{
String name;
int age;
//생성자1
Person(){
this("이름없음", 1); // 생성자2를 호출
}
//생성자2
Person(String name, int age){
this.name = name;
this.age = age;
}
// class형을 반환
Person returnItSelf() {
return this;
}
}
public class CallAnotherConst {
public static void main(String[] args) {
Person noName = new Person();
System.out.println(noName.name);
System.out.println(noName.age);
Person p = noName.returnItSelf(); // this 값을 클래스 변수에 대입
System.out.println(p);
System.out.println(noName);
}
}
'프로그래밍 언어 > Java' 카테고리의 다른 글
10. [Java] static 변수 (0) | 2022.02.01 |
---|---|
09. [Java] 객체 간 협력 (0) | 2022.01.31 |
07. [Java] 정보은닉 with 접근제어자 (public&private) (0) | 2022.01.31 |
06. [Java] 인스턴스 생성 (new) (0) | 2022.01.31 |
05. [Java] 클래스의 기본구조 & Main 함수 사용 (0) | 2022.01.31 |