Encapsulation: private fields, getters, setters · カプセル化:private フィールド、ゲッター、セッター
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.
データの保護
- カプセル化とは、オブジェクトのデータを非公開にし、メソッドを通じてのみ変更することを意味します。
- これによりデータが安全に保たれます。他のコードは不適切な値を入れることができません。
- 主要な手段は
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().
アクセッサ(ゲッター)
- フィールドが private なので、それを読み取るための
publicメソッドを追加します。 - フィールドを返すメソッドを アクセッサ または ゲッター と呼びます。
- 通常は
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.
ミューテータ(セッター)
- フィールドを変更するメソッドを ミューテータ または セッター と呼びます。
- 新しい値を確認し、不適切な場合は拒否することができます。
- 下のように、
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 インスタンス
- インスタンスフィールドは1つのオブジェクトに属します。各オブジェクトに固有です。
staticフィールドはクラス自体に属し、すべてのオブジェクトで共有されます。- 下のように、
countは anyRobotが作成されるたびに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にし、ゲッターやセッター経由でアクセスしてください。 - セッターは格納する前に値を確認できます。
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.
あなたも試してみよう
- 各クラスを埋め込み、そのprivateなデータが安全なメソッドを介してのみ変更されるようにしてください。
- 隠された 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 を完成させなさい。コンストラクタは private フィールドに int degrees を格納します。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. · 実行ボタンをクリックして出力を確認してください。