| 접근제어자 | 클래스 내부 | 패키지 내부 | 상속한 클래스 | 전체 공개 |
|---|---|---|---|---|
| public | ✅ | ✅ | ✅ | ✅ |
| protected | ✅ | ✅ | ✅ | ❌ |
| default | ✅ | ✅ | ❌ | ❌ |
| private | ✅ | ❌ | ❌ | ❌ |
✅ 캡슐화가 된 데이터에 접근 방법
- 캡슐화가 잘 적용된 클래스는 내부 데이터를
private으로 보호하고 있다.- 데이터 조회나 변경이 필요한 경우 안전하게 접근하기 위해 게터와 세터 메서드를 사용한다.
public class Person {
private String secret;
public String getSecret() {
return this.secret; // ✅ 객체의 secret 속성 반환
}
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person();
p1.secret; // ❌ 직접 접근 불가능
String newSecret = p1.getSecret(); // ✅ 게터를 활용해 접근가능
}
}
public class Person {
private String secret;
public void setSecret(String secret) {
this.secret = secret; // ✅ secret 속성 설정 및 변경
}
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person();
p1.secret = "password"; // ❌ 직접접근, 변경 불가능
p1.setSecret("newPassword"); // ✅ 세터를 활용해 접근, 변경가능
}
}
public class DataStore {
String store;
}
DataStore dataStore = new DataStore();
dataStore.store = "B"; // ❌ 의문의 핵폭발 발생!
store변수에 문자열 "B"가 들어오면 핵폭발이 발생하는 시스템이다.
public class DataStore {
private String store;
}
DataStore dataStore = new DataStore();
dataStore.store = "B"; // ❌ 컴파일 오류! 직접 접근 불가!
store변수에private접근제어자를 설정하면 외부에서 직접 변경할 수 없게 되어 핵폭발을 막을 수 있다.- 하지만 데이터를 아예 사용할 수 없게 되었다. 어떤 데이터도 저장할 수 없다면 이 클래스는 쓸모가 없어진다.
public class DataStore {
private String store;
public void setStore(String data) {
this.store = data;
}
}
DataStore dataStore = new DataStore();
dataStore.setStore("B"); // ❌ 다시 핵폭발 발생!
store변수는private이지만 세터를 통해 외부에서 값을 변경할 수 있다.- 하지만 다시 "B"를 넣으면 핵폭발이 발생한다.
public class DataStore {
private String store;
public void setStore(String data) {
if ("B".equals(data)) {
System.out.println("❌ 'B'는 입력할 수 없습니다!");
} else {
this.store = data;
}
}
}
"B"가 입력되면 입력할 수 없다는 메세지를 제공한다.- 데이터는 안전하게 저장되고 원하지 않는 값이 들어오는 것도 막을 수 있다.