접근 제어자 (access modifier)
private
같은 클래스에서만 접근 가능
(default)
같은 패키지에서만 접근 가능
protected
같은 패키지 또는 하위 클래스에서만 접근 가능
public
모든 클래스에서 접근 가능
Note
- 클래스에는 public 또는 (default) 만 붙힐 수 있다.
- 멤버에는 모든 접근 제어자를 붙힐 수 있다.
캡슐화
클래스의 특정 변수와 메소드를 외부로부터 감추고 직접 접근할 수 없도록 하는 것을 의미한다.
접근 제어자를 사용해 캡슐화를 구현할 수 있다.
class Time {
public int hour;
public int minute;
public int second;
}
public class Main {
public static void main(String[] args) {
Time t = new Time();
t.hour = 25; // t.hour == 25 (inconsistent data)
}
}
class Time {
private int hour;
private int minute;
private int second;
public int getHour() { return hour; }
public void setHour(int minute) {
if (hour < 0 || hour > 23) return;
this.hour = hour;
}
}
class Time {
public int hour;
public int minute;
public int second;
}
public class Main {
public static void main(String[] args) {
Time t = new Time();
t.setHour(25); // t.hour == 0 (consistent data)
}
}
캡슐화를 하면 데이터의 consistency를 보장할 수 있게 된다.
'프로그래밍 언어 > Java' 카테고리의 다른 글
call by value vs call by reference (0) | 2023.01.05 |
---|---|
JVM, JRE, JDK (0) | 2023.01.04 |
접근 제어자 (0) | 2022.06.03 |
클래스 클래스 (0) | 2022.05.31 |
인텔리제이 단축키 (0) | 2022.05.31 |