
1. 접근자(getters) & 설정자 (setters)
외부에서 필드를 사용할 일이 있을 때, 필드에 접근하게 해주는 특수한 메소드.
private한 필드에 접근하기 위해선 getter, setter을 통해 우회적으로 접근한다.
>> 캡슐화 가능!
(객체의 내부 구현을 외부로부터 감추고, 객체와 상호작용하기 위한 인터페이스를 제공하는 개념)
getter - 읽기 (멤버 변수의 값을 외부에서 읽을 수 있음. 멤버 변수의 값을 반환)
setter - 쓰기 (멤버 변수의 값을 외부에서 변경할 수 있음. 멤버 변수의 값을 설정)
* getter는 무조건!! 다 만들어라!! 단, setter는 별로 안좋다. 추천 x 직접 만들어라.
변경될 수 있는 것 (필요한 것)만 setter를 만들어서 사용.
(setter이름을 바꿔주는게 눈에 더 잘 보임. ex) setPw보다 changePassword 가 더 잘읽힘. setPw나 changePassword는 구조나, 기능은 똑같음)
* getter, setter는 초기화할 때 쓰는게 (초기화 때는 생성자) 아니라, 시간이 흐르고 난 뒤,
(값을 바꾼다거나, 값을 확인하거나…) 사용
getter, setter 예시
package ex03.test;
class Account {
private int number; // 1111
private String pw; // 8877
private String author; // 최주호
private int balance; // 1000
public Account(int number, String pw, String author, int balance) {
this.number = number;
this.pw = pw;
this.author = author;
this.balance = balance;
}
public int getNumber() {
return number;
}
public String getPw() {
return pw;
}
public String getAuthor() {
return author;
}
public int getBalance() {
return balance;
}
public void chanagePassword(String pw){
this.pw = pw;
}
public void changeAuthor(String author) {
this.author = author;
}
public void deposit(int amount){
this.balance = this.balance + amount;
}
public void withdraw(int amount){
this.balance = this.balance - amount;
}
public void setBalance(int balance){
this.balance = balance;
}
}
public class ScopeEx02 {
public static void main(String[] args) {
// 1. 계좌생성 (2023.12.25)
Account account = new Account(1111, "8877", "최주호", 1000);
// 2. 입금 (2023.01.10) - 5000 //이게 더 편하고 간단하다!
account.deposit(5000);
// 3. 비밀번호 변경 (2023.01.20) - 9988
account.chanagePassword("9988");
// 4. 계명 - 이름 변경 (2023.02.20) - 홍길동
account.changeAuthor("홍길동");
// 5. 계좌번호변경 - 은행 - 불가능합니다.
// 6. 출금 - 500원
account.withdraw(500);
// 7. 5000 원 입금 //비효율적. 길다.
int currentBalance = account.getBalance();
int balance = currentBalance + 5000;
account.setBalance(balance);
}
}
객체 지향에서 모든 상태값은 private니까 getter, setter이 존재
* toString은 전체값을 확인하는 거지, 값 하나씩 볼 수 는 없음

- 인텔리J에서는 alt + insert 를 사용하면 GETTER & SETTER을 손쉽게 사용할 수 있다.

- getter과 setter을 사용해서 필드 값에 접근했다.

- 바뀐 것 확인.
Share article