자신의 인스턴스 주소값을 저장하는 참조 변수
자바에 의해 자동으로 생성됨
모든 인스턴스 내에는 this가 존재하며, 자신의 인스턴스 주소가 저장됨
-> 인스턴스마다 this에 저장된 값이 서로 다름
자신의 인스턴스 내의 멤버(멤버변수 or 멤버메서드)에 접근
로컬변수와 인스턴스 변수의 이름이 같을 때 인스턴스 변수 지정 용도로 사용
< 레퍼런스 this 사용 기본 문법 >
자신의 클래스 내의 생성자 또는 메서드 내에서
this.인스턴스 변수
또는this.메서드()
형태로 접근
public static void main(String[] args) {
Person p = new Person(); // 오류 발생
// 파라미터 생성자를 정의했으므로 파라미터 값 필요
Person p = new Person("최보민", 23);
p.showPersonInfo();
}
class Person {
String name;
int age;
public Person(String name, int age) {
// 메서드 오버라이딩 (단축키 : ctrl + alt + s -> o)
this.name = name;
this.age = age;
// this 뒤에 name과 age는 로컬변수 name과 age를 가리키고
// name과 age는 클래스 내의 멤버변수 name과 age를 가리킨다
}
public void showPersonInfo() {
System.out.println("이름 : " + name);
System.out.println("나이 : " + age);
}
}
자신의 생성자 내에서 또 다른 생성자 호출
자신의 인스턴스에 접근하여 다른 오버로딩된 생성자 호출 용도로 사용
생성자 오버로딩 시 인스턴스 변수에 대한 초기화 코드가 중복되는데 초기화 코드 중복 제거 용도로 사용
여러 생성자에서 각각 인스턴스 변수를 중복으로 초기화X,
하나의 생성자에서만 초기화 코드 작성 후 나머지 생성자에서는 해당 초기화 코드를 갖는 생성자를 호출하여 초기화할 값만 전달 후 인스턴스 변수 초기화 수행
메서드 오버로딩 시 코드 중복 제거를 위해 하나의 메서드에서만 작업 수행,
나머지 메서드는 해당 메서드를 호출하여 데이터 전달하는 것과 동일
(메서드는 메서드 이름(), 생성자는 this()로 호출)
< 생성자 this() 호출 기본 문법 >
생성자 내의 첫 번째 라인에서
this([데이터...]);
public static void main(String[] args) {
Date d = new Date();
// 기본 생성자를 정의했기 때문에 파라미터값이 없어도 사용 가능
System.out.println(d.year + " / " + d.month + " / " + d.day);
// [2022 / 10 / 11] 출력됨
Date d2 = new Date(1990);
System.out.println(d2.year + " / " + d2.month + " / " + d2.day);
// [1990 / 10 / 11] 출력됨
}
Date d3 = new Date(1990, 6);
System.out.println(d3.year + " / " + d3.month + " / " + d3.day);
// [1990 / 6 / 11] 출력됨
}
Date d4 = new Date(1990, 6, 28);
System.out.println(d4.year + " / " + d4.month + " / " + d4.day);
// [1990 / 6 / 28] 출력됨
}
Class Date {
int year;
int month;
int day;
public Date() {
// 기본 생성자 정의
this(2022, 10, 11);
// 년, 월, 날짜 모두 초기화
//this()를 사용하지 않을 경우
// year = 2022;
// month = 10;
// day = 11;
// 위의 코드를 모두 써야함
// this()를 사용하면 코드의 중복을 줄일 수 있음
}
public Date(int year) {
// year의 값을 전달받아 초기화
this(year, 10, 11);
// 월과 날짜만 초기화
}
public Date(int year, int month) {
// year과 month의 값을 전달받아 초기화
this(year, month, 11);
// 날짜만 초기화
}
public Date(int year, int month, int day) {
// 모든 인스턴스 변수 데이터를 전달받아 초기화하는 생성자 정의
this.year = year;
this.month = month;
this.day = day;
// this가 붙은 year, month, day는 로컬변수를 가리키고
// this가 붙지 않은 year, month, day는 멤버변수를 가리킴
}
}
private 접근제한자를 적용한 멤버 변수 accountNo, ownerName, balance를 선언하고, 파라미터 3개를 전달받아 초기화하는 생성자 정의
public static void main(String[] args) {
Account acc = Account("111-1111-111", "최보민", 100000);
acc.showAccountInfo();
}
class Account {
String accountNo;
String ownerName;
int balance;
public Account(String accountNo, String ownerName, int balance) {
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);
}
}