접근 제어(access control)란 클래스의 멤버에 접근하는 것을 제어하는 것이다.
아래는 지정자의 예제이다
package ex04;
class A {
private int a; //전용
int b; //디폴트
public int c; //공용
}
public class Test {
public static void main(String[] args) {
A obj = new A();
obj.a = 10; //전용 멤버라 접근이 안됨
obj.b = 20; //디폴트 멤버는 접근 가능
obj.c = 30; //공용 멤버는 접근 가능
}
}
접근자와 설정자
package ex04;
class Account {
//필드가 모두 private로 선언되었으니 클래스 내부에서만 사용가능
private int regNumber;
private String name;
private int balance;
//접근자와 설정자를 사용
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getBalance() {return balance;}
public void setBalance(int balance) {this.balance = balance;}
}
public class AccouontTest {
public static void main(String[] args) {
Account obj = new Account();
obj.setName("Tom");
obj.setBalance(100000);
System.out.println("이름은 " + obj.getName() +
" 통잔 잔고는 " + obj.getBalance() + "입니다.");
}
}
//이름은 Tom 통잔 잔고는 100000입니다.
안전한 배열 만들기
package ex04;
class SafeArray {
private int a[];
public int length;
public SafeArray(int size) {
a = new int[size];
length = size;
}
public int get(int index) {
if (index >= 0 && index < length) {
return a[index];
}
return -1;
}
//설정자에서 잘못된 인덱스를 번호를 차단할 수 있다.
public void put(int index, int value) {
if (index >= 0 && index < length) {
a[index] = value;
} else {
System.out.println("잘못된 인덱스 " + index);
}
}
}
public class SafeArrayTest {
public static void main(String[] args) {
SafeArray array = new SafeArray(3);
for (int i = 0; i < (array.length + 1); i++) {
array.put(i, i * 10);
}
}
}
//잘못된 인덱스 3