은닉:private 필드, getter, setter
이 페이지는 최신 브라우저(SharedArrayBuffer 지원)가 필요합니다. Chrome, Edge, Firefox 또는 Safari를 최신 버전으로 업데이트해 주세요.
데이터 보호
- Encapsulation은 객체의 데이터를 숨기고 메서드를 통해만 변경하도록 하는 것입니다.
privateblocks direct access from unrelated outside code. It does not validate values: constructors and mutating methods must enforce the object’s rules themselves.- 주요 도구로 사용되는 단어는
private와public입니다.
private 필드
- 인스턴스 변수를
private로 표시하여 관련 없는 클래스의 코드가 직접 접근할 수 없게 하십시오. - 동일한 클래스 내부의 메서드는 여전히 사용할 수 있습니다.
- 이는 AP CSA의 표준 스타일입니다: 필드는
private입니다. 첫 번째 예시는 의도적으로 음수 시작 값을 허용합니다;main은 같은 클래스에 있으므로 해당-private 필드를 읽을 수 있습니다.-50.0을 출력하여 검증이 누락되었음을 보여줍니다.
English
public class BankAccount {
private double balance; // hidden from outside code
public BankAccount(double start) {
this.balance = start;
}
public static void main(String[] args) {
BankAccount account = new BankAccount(-50);
System.out.println(account.balance); // -50.0: private alone does not validate
}
}
액세서러(Getter)
- 필드가 private이므로 이를 읽기 위한
public메서드를 추가합니다. - 필드를 반환하는 메서드를 액세서러 또는 getter라고 부릅니다.
- 일반적으로
get로 시작하며, 예로getBalance()를 들 수 있습니다.
English
public class BankAccount {
private double balance;
public BankAccount(double start) {
this.balance = start;
}
public double getBalance() {
return this.balance;
}
public static void main(String[] args) {
BankAccount account = new BankAccount(100);
System.out.println(account.getBalance()); // 100.0
}
}
뮤테이터(Setter)
- 객체 상태를 변경하는 메서드를 **무효화자(mutator)**라고 합니다. **세터(setter)**는 그 중 하나로, 일반적으로 필드에 제공된 값을 설정합니다;
deposit은 잔액을 증가시키는 무효화자입니다. - 새 값이 적절함을 먼저 확인하고 부적절한 값은 거절할 수 있습니다.
- 아래에서 컨스트럭터는 음수 시작값을 거부하고
deposit은 비양수 금액을 무시합니다. 이 예제들은 유한한double값을 가정하며, 표시된 검사는 모든 가능한 은행 요구사항이 아닌 명시된 규칙을 강제합니다.
English
public class BankAccount {
private double balance;
public BankAccount(double start) {
if (start < 0) {
throw new IllegalArgumentException("Start must be nonnegative");
}
this.balance = start;
}
public void deposit(double amount) {
if (amount > 0) {
this.balance = this.balance + amount;
}
}
public double getBalance() {
return this.balance;
}
public static void main(String[] args) {
BankAccount account = new BankAccount(100);
account.deposit(-500);
System.out.println(account.getBalance()); // 100.0
account.deposit(50);
System.out.println(account.getBalance()); // 150.0
try {
new BankAccount(-50);
} catch (IllegalArgumentException error) {
System.out.println("Negative start rejected");
}
}
}
static vs 인스턴스
- 인스턴스 필드는 하나의 객체에 속하며, 각 객체는 고유의 필드를 가집니다.
- A
static필드는 클래스 자체에 속하며, 모든 객체가 공유합니다. - Below,
countrises by 1 every time aRobotis constructed. It counts constructions, not the number of objects still alive; discarding a reference does not decrease it.
English
public class Robot {
private static int count = 0; // shared by all robots
public Robot() {
count = count + 1;
}
public static int getCount() {
return count;
}
public static void main(String[] args) {
Robot first = new Robot();
Robot second = new Robot();
System.out.println(Robot.getCount()); // 2 constructions
}
}
toString()
toString()는 객체를 설명하는 텍스트를 반환합니다.- Java calls it automatically when you print the object or join it with text using
+. The inheritedObject.toString()uses the class name,@and a hexadecimal hash code; that text is not a guaranteed memory address. - 매개변수가 없으며
String를 반환합니다.
English
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "(" + this.x + ", " + this.y + ")";
}
public static void main(String[] args) {
Point point = new Point(3, 4);
System.out.println(point); // (3, 4)
System.out.println("Point: " + point); // Point: (3, 4)
}
}
흔한 실수
- 필드를
private로 만들고 getter 및 setter를 통해 접근하세요. - 세터(value)는 저장 전에 값을 확인할 수 있습니다.
이제 직접 해보기
- 각 클래스를 명시된 생성자 및 메서드 약정에 따라 채우십시오.
private만으로는 이를 강제하지 않습니다. - 숨겨진 Harness가 객체를 생성하고, 메서드를 호출하며, 결과를 확인합니다.
- These class tasks have no standalone
mainand no Run button. Check answer compiles your class with the supplied harness, runs its calls and gives feedback. The complete examples above have their own Run buttons.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
BankAccount을 완성하십시오. start이 음수가 아니며 모든 합산 연산이 int에 적합하다고 가정하십시오. balance은 비공개로 유지하십시오. deposit(amount)는 금액이 0보다 클 때만 추가합니다. withdraw(amount)은 금액이 0보다 크고 잔액 이상이지 않을 때(과잉 인출 방지)에만 차감합니다. getBalance()은 잔액을 반환합니다.
출력을 보려면 '실행'을 클릭하세요.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
Temperature를 완성하세요. 컨스트럭터는 int degrees를 private 필드에 저장합니다. toString()는 각도를 표시한 뒤 C를 붙여 반환합니다. (21인 경우 21C를 반환합니다.)
출력을 보려면 '실행'을 클릭하세요.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
Widget를 완성하세요. private static 필드 count는 0으로 시작합니다. Widget 객체가 생성될 때마다 컨스트럭터에서 count에 1을 더합니다. static 메소드 getCount()는 제작된 위젯의 개수를 반환합니다.
출력을 보려면 '실행'을 클릭하세요.