Encapsulation: private fields, getters, setters · 은닉:private 필드, getter, setter
Protect your data
- Encapsulation means hiding an object's data and only changing it through methods.
- This keeps the data safe. Other code cannot put a bad value into it.
- The main tools are the words
privateandpublic.
데이터 보호
- Encapsulation은 객체의 데이터를 숨기고 메서드를 통해만 변경하도록 하는 것입니다.
- 이를 통해 데이터를 안전하게 유지하며, 다른 코드에서 잘못된 값을 넣을 수 없습니다.
- 주요 도구로 사용되는 단어는
private와public입니다.
private fields
- Mark instance variables
privateso code outside the class cannot touch them directly. - Methods inside the same class can still use them.
- This is the normal style for AP CSA: fields are
private.
private 필드
- 인스턴스 변수를
private로 표시하여 클래스 외부의 코드가 직접 접근하지 못하게 합니다. - 동일한 클래스 내부의 메서드는 여전히 사용할 수 있습니다.
- 이는 AP CSA의 표준 스타일입니다: 필드는
private입니다.
public class BankAccount {
private double balance; // hidden from outside code
public BankAccount(double start) {
this.balance = start;
}
}
Accessors (getters)
- A field is private, so we add a
publicmethod to read it. - A method that returns a field is called an accessor or getter.
- It usually starts with
get, likegetBalance().
액세서러(Getter)
- 필드가 private이므로 이를 읽기 위한
public메서드를 추가합니다. - 필드를 반환하는 메서드를 액세서러 또는 getter라고 부릅니다.
- 일반적으로
get로 시작하며, 예로getBalance()를 들 수 있습니다.
public class BankAccount {
private double balance;
public BankAccount(double start) {
this.balance = start;
}
public double getBalance() {
return this.balance;
}
}
Mutators (setters)
- A method that changes a field is called a mutator or setter.
- It can check the new value first and refuse a bad one.
- Below,
depositignores a negative amount, so the balance stays safe.
뮤테이터(Setter)
- 필드를 변경하는 메서드를 뮤테이터 또는 setter라고 부릅니다.
- 새 값이 적절함을 먼저 확인하고 부적절한 값은 거절할 수 있습니다.
- 아래에서
deposit는 음수 금액을 무시하므로 잔고는 안전하게 유지됩니다.
public class BankAccount {
private double balance;
public BankAccount(double start) {
this.balance = start;
}
public void deposit(double amount) {
if (amount > 0) {
this.balance = this.balance + amount;
}
}
public double getBalance() {
return this.balance;
}
}
static vs instance
- An instance field belongs to one object. Each object has its own.
- A
staticfield belongs to the class itself — it is shared by all objects. - Below,
countrises by 1 every time anyRobotis built.
static vs 인스턴스
- 인스턴스 필드는 하나의 객체에 속하며, 각 객체는 고유의 필드를 가집니다.
- A
static필드는 클래스 자체에 속하며, 모든 객체가 공유합니다. - 아래에서
count는 어떤Robot이 생성될 때마다 1씩 증가합니다.
public class Robot {
private static int count = 0; // shared by all robots
public Robot() {
count = count + 1;
}
public static int getCount() {
return count;
}
}
toString()
toString()returns text that describes the object.- Java calls it automatically when you print the object or join it with
+. - It takes no parameters and returns a
String.
toString()
toString()는 객체를 설명하는 텍스트를 반환합니다.- 객체를 출력하거나
+와 결합할 때 Java가 자동으로 호출합니다. - 매개변수가 없으며
String를 반환합니다.
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 + ")";
}
}
Common mistakes
- Make fields
privateand reach them through getters and setters. - A setter can check a value before storing it.
흔한 실수
- 필드를
private로 만들고 getter 및 setter를 통해 접근하세요. - 세터(value)는 저장 전에 값을 확인할 수 있습니다.
Now you try
- Fill in each class so its private data is changed only through safe methods.
- A hidden Harness builds the object, calls the methods, and checks the results.
- Press Run to compile, then Check answer.
이제 직접 해보기
- 각 클래스를 완성하여私密 데이터가 안전한 메서드를 통해 오직 변경되도록 하십시오.
- 숨겨진 Harness가 객체를 생성하고, 메서드를 호출하며, 결과를 확인합니다.
- 컴파일하려면 Run을 누르고, 그 후 Check answer를 누르십시오.
Complete BankAccount. Keep balance private. deposit(amount) adds the amount only if it is greater than 0. withdraw(amount) subtracts only if the amount is greater than 0 and not more than the balance (no overdraft). getBalance() returns the balance. · BankAccount를 완성하세요. balance는 private으로 유지해야 합니다. deposit(amount)는 금액이 0보다 클 때만 잔고에 더합니다. withdraw(amount)는 금액이 0보다 크고 또한 잔고 이하일 때만 차감합니다(과잉 인출 금지). getBalance()는 잔고를 반환합니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Complete Temperature. The constructor stores an int degrees in a private field. toString() returns the degrees followed by C — for 21 it returns 21C. · Temperature를 완성하세요. 컨스트럭터는 int degrees를 private 필드에 저장합니다. toString()는 각도를 표시한 뒤 C를 붙여 반환합니다. (21인 경우 21C를 반환합니다.)
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Complete Widget. A private static field count starts at 0. Every time a Widget is built, the constructor adds 1 to count. The static method getCount() returns how many widgets have been built. · Widget를 완성하세요. private static 필드 count는 0으로 시작합니다. Widget 객체가 생성될 때마다 컨스트럭터에서 count에 1을 더합니다. static 메소드 getCount()는 제작된 위젯의 개수를 반환합니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.