Encapsulation: private fields, getters, setters · 封装:私有字段、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)
- 字段是私有的,所以我们加一个
public方法来读取它。 - 返回字段的方法叫作访问器(accessor)或 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)
- 修改字段的方法叫作修改器(mutator)或 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 与实例
- 一个实例(instance)字段属于某一个对象。每个对象都有它自己的一份。
- 一个
static字段属于类本身 —— 它被所有对象共享。 - 下面,每当任何一个
Robot被创建时,count都会加 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 访问。 - setter 可以在存储前先检查值。
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 会创建对象、调用方法并检查结果。
- 按运行来编译,然后按检查答案。
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 保持私有。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 存进一个私有字段。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。一个私有的 static 字段 count 初始为 0。每当创建一个 Widget 时,构造方法就让 count 加 1。static 方法 getCount() 返回一共创建了多少个 widget。
Click Run to see the output here. · 点击“运行”查看此处输出。