this 키워드
- 자신의 인스턴스 주소값을 저장하는 참조 변수
-> 개발자가 생성하는 것이 아니라 자바에 의해 자동으로 생성됨
- 모든 인스턴스 내에는 this가 존재하며, 자신의 인스턴스 주소가 저장됨
-> 즉, 인스턴스마다 this에 저장된 값이 다름
1. 레퍼런스 this
- 자신의 인스턴스 내의 멤버에 접근(멤버변수 or 멤버메서드)
- 주로, 로컬변수와 인스턴스 변수(=멤버변수)의 이름이 같을 때 인스턴스 변수를 지정하는 용도로 사용
< 레퍼런스 this 사용 기본 문법 >
자신의 클래스 내의 생성자 또는 메서드 내에서 this.인스턴스 변수 또는 this.메서드() 형태로 접근
class Person {
// 멤버변수 선언
private String name;
private int age;
// 이름, 나이를 전달받아 초기화하는 파라미터 생성자 정의
// Alt + Shift + S -> O
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
// 멤버변수 Getter/Setter 메서드 정의
// Alt + Shift + S -> R
public String getName() {
// 로컬변수와 멤버변수 이름이 중복되지 않으므로
// 레퍼런스 this를 생략 가능!
return name; // return this.name; 과 동일함
}
public void setName(String name) {
// 메서드 내의 로컬변수와 클래스 내의 멤버변수의 이름이 동일할 경우
// 메서드 내에서 변수 지정 시 로컬 변수가 지정됨
// this.name = name; // 로컬 변수 name값을 다시 로컬변수 name에 저장하는 코드
// 로컬변수와 멤버변수를 구별하기 위해서는 멤버변수 앞에
// 레퍼런스 this를 사용하여 해당 인스턴스에 접근하는 코드로 사용해야 함
// -> 외부에서 멤버변ㅅ name에 접근 시 참조변수명.name형태로 접근
// -> 내부에서 멤버변수 name에 접근 시 this.name형태로 접근
this.name = name; // 로컬변수 name값을 멤버변수 name에 저장하는 코드
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// showPersoninfo() 메서드를 정의해서 이름과 나이를 출력
public void showPeronInfo() {
// 클래스 내의 메서드에서 멤버변수에 접근하기
System.out.println("이름: "+name); // this.name
System.out.println("나이: "+age); // this.age
}
}
Person p = new Person("임소언", 20);
p.showPeronInfo();
// p.name = "임소언"; // 오류 발생!
p.setName("임소언");
p.setAge(20);
p.showPeronInfo();
Test
package this_;
public class Test {
public static void main(String[] args) {
// "111-1111-111", "홍길동", 0 초기값 인스턴스 생성
Account acc = new Account("111-1111-1111", "홍길동", 0);
// showAccountInfo() 메서드 호출
acc.showAccountInfo();
}
}
/*
* Account 클래스 생성
* - 멤버변수 : accountNo, ownerName, balance 선언(private 접근제한자 사용)
* - 파라미터 3개를 전달받아 초기화하는 파라미터 생성자 정의
* - Getter/Setter 메서드 정의
* - showAccountInfo() 메서드 정의 -> 계좌번호, 예금주명, 현재잔고 출력
*/
class Account {
private String accountNo;
private String ownerName;
private int balance;
public Account(String accountNo, String ownerName, int balance) {
// 인스턴스 변수와 로컬변수 이름이 동일하므로
// 인스턴스 변수(좌변)의 앞에 레퍼런스 this 를 붙여서 구별
this.accountNo = accountNo;
this.ownerName = ownerName;
this.balance = balance;
}
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public void showAccountInfo() {
System.out.println("계좌번호 : " + accountNo);
System.out.println("예금주명 : " + ownerName);
System.out.println("현재잔고 : " + balance + "원");
}
}
생성자 this()
- 자신의 생성자 내에서 자신의 또 다른 생성자를 호출
- 레퍼런스 this 사용과 동일하게 자신의 인스턴스에 접근하여 다른 오버로딩 된 생성자를 호출하는 용도로 사용
- 생성자 오버로딩시 인스턴스 변수에 대한 초기화 코드가 중복되는데 초기화 코드 중복을 제거하는 용도로 사용
-> 여러 생성자에서 각각 인스턴스 변수를 중복으로 초기화하지 않고 하나의 생성자에서만 초기화 코드를 작성한 뒤 나머지 생성자에서는 해당 초기화 코드를 갖는 생성자를 호출하여 초기화할 값만 전달 후 대신 인스턴스 변수를 초기화
-> 메서드 오버로딩 시 코드의 중복을 제거하기 위해서 하나의 메서드에서만 작업을 수행하고 나머지 메서드는 해당 메서드를 호출하여 데이터를 전달하는 것과 동일함
(단 메서드는 메서드이름()으로 호출, 생성자는 this()로 호출하는 차이)
< 생성자 this() 호출 기본 문법 >
생성자 내의 첫 번째 라인에서
this([데이터...]);
class MyDate {
int year;
int month;
int day;
// Alt + Shift + S -> O
// 기본 생성자
public MyDate() {
// 연도 : 1900, 월 : 1, 일 : 1 로 초기화
// 자신의 생성자 내에서 다른 오버로딩 된 생성자 호출!
this(1900, 1, 1); // 다른 실행 코드보다 무조건 먼저 실행되어야 함!
// => public MyDate(int year, int month, int day) { } 생성자가 호출됨
System.out.println("MyDate() 생성자 호출됨!");
// year = 1900;
// month = 1;
// day = 1;
// => 인스턴스 변수 초기화 코드
// this(1900,1,1); // 컴파일 에러 발생
// => Constructor call must be the first statement in a constructor
// => 생성자 내의 다른 실행코드보다 아래쪽에 생성자 this()가 올 수 없다!
}
// 연도(year)만 전달받고, 나머지는 1월 1일로 초기화를 하는 생성자
public MyDate(int year) {
// MyDate(int, int, int) 생성자를 호출하여
// 전달받은 연도(year)와 1월 1일 값을 전달하여 대신 초기화
this(year, 1, 1);
System.out.println("MyDate(int) 생성자 호출됨!");
// this.year = year;
// month = 1;
// day = 1;
}
// 연도(year), 월(month)을 전달받고 나머지는 1일로 초기화를 하는 생성자
public MyDate(int year, int month) {
// MyDate(int, int, int) 생성자를 호출하여
// 전달받은 연도(year), 월(month)와 1의 값을 전달하여 대신 초기화
this(year, month, 1);
System.out.println("MyDate(int, int) 생성자 호출됨!");
// this.year = year;
// this.month = month;
// day = 1;
}
// 연도(year), 월(month), 일(day)를 전달받고 초기화를 하는 생성자
public MyDate(int year, int month, int day) {
System.out.println("MyDate(int, int, int) 생성자 호출됨!");
this.year = year;
this.month = month;
this.day = day;
}
}
// MyDate() 생성자 호출 => 1900년 1월 1일로 초기화
MyDate d1 = new MyDate();
System.out.println(d1.year + "/" + d1.month + "/" + d1.day);
System.out.println("---------------------------------------");
//MyDate(int) 생성자 호출 => 2023년 1월 1일로 초기화
MyDate d2 = new MyDate(2023);
System.out.println(d2.year + "/" + d2.month + "/" + d2.day);
System.out.println("---------------------------------------");
//MyDate(int) 생성자 호출 => 2023년 9월 1일로 초기화
MyDate d3 = new MyDate(2023, 9);
System.out.println(d3.year + "/" + d3.month + "/" + d3.day);
System.out.println("---------------------------------------");
//MyDate(int) 생성자 호출 => 2023년 9월 11일로 초기화
MyDate d4 = new MyDate(2023, 9, 11);
System.out.println(d4.year + "/" + d4.month + "/" + d4.day);
TEST
/*
* Account2 클래스 생성
* - 멤버변수 : accountNo, ownerName, balance 선언
* - 생성자 오버로딩(레퍼런스 this와 생성자 this() 활용)
* 1) 기본 생성자("111-1111-111", "홍길동", 0)
* 2) 계좌번호를 전달받아 초기화하는 생성자
* 3) 계좌번호, 예금주명을 전달받아 초기화하는 생성자
* 4) 계좌번호, 예금주명, 현재잔고를 전달받아 초기화하는 생성자
* -> 초기화 작업을 수행하는 생성자
* - showAccountInfo() 메서드 정의 -> 계좌번호, 예금주명, 현재잔고 출력
*/
class Account2 {
String accountNo;
String ownerName;
int balance;
// 기본 생성자
public Account2() {
this("111-1111-111","홍길동",0);
System.out.println("Account2() 생성자 호출됨!");
}
// 계좌번호
public Account2(String accountNo) {
this(accountNo, "홍길동", 0);
System.out.println("Account2(String) 생성자 호출됨!");
// accountNo = "111-1111-111";
// ownerName = "홍길동";
// balance = 0;
}
// 계좌번호, 예금주명
public Account2(String accountNo, String ownerName) {
this(accountNo, ownerName, 0);
System.out.println("Account2(String, String) 생성자 호출됨!");
// accountNo = "111-1111-111";
// ownerName = "홍길동";
// balance = 0;
}
// 계좌번호, 예금주명, 현재잔고
public Account2(String accountNo, String ownerName, int balance) {
System.out.println("Account2(String, String, int) 생성자 호출됨!");
this.accountNo = accountNo;
this.ownerName = ownerName;
this.balance = balance;
}
public void showAccountInfo() {
System.out.println("계좌번호 : " + accountNo);
System.out.println("예금주명 : " + ownerName);
System.out.println("현재잔고 : " + balance + "원");
}
}
Account2 acc = new Account2();
acc.showAccountInfo();
System.out.println("----------------------");
Account2 acc2 = new Account2("999-9999-999");
acc2.showAccountInfo();
System.out.println("----------------------");
Account2 acc3 = new Account2("999-9999-999", "이순신");
acc3.showAccountInfo();
System.out.println("----------------------");
Account2 acc4 = new Account2("999-9999-999", "이순신", 10000);
acc4.showAccountInfo();
System.out.println("----------------------");
'⛏️ > JAVA' 카테고리의 다른 글
[JAVA] 16. Static, 싱글톤 (0) | 2023.09.12 |
---|---|
[JAVA] 15. 패키지 (0) | 2023.09.11 |
[JAVA] 13. 가변형 인자 (0) | 2023.09.11 |
[JAVA] 12. 배열 (0) | 2023.09.05 |
[JAVA] 11. 생성자(Constructor) (0) | 2023.08.30 |