Encapsulation: private fields, getters, setters · Encapsulation: các trường private, getters, setters
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.
Bảo vệ dữ liệu của bạn
- Encapsulation có nghĩa là giấu dữ liệu của đối tượng và chỉ thay đổi nó thông qua các phương thức.
- Điều này giữ cho dữ liệu an toàn. Mã khác không thể đưa giá trị sai vào đó.
- Các công cụ chính là các từ
privatevà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.
Trường private
- Đánh dấu biến instance là
privateđể mã bên ngoài lớp không thể chạm trực tiếp vào chúng. - Các phương thức bên trong cùng lớp vẫn có thể sử dụng chúng.
- Đây là phong cách tiêu chuẩn cho AP CSA: các trường dữ liệu là
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().
Bộ truy cập (getters)
- Vì một trường là riêng tư, nên chúng ta thêm một phương thức
publicđể đọc nó. - Một phương thức trả về một trường được gọi là bộ truy cập hoặc getter.
- Nó thường bắt đầu bằng
get, như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.
Bộ thay đổi (setters)
- Một phương thức thay đổi một trường được gọi là bộ thay đổi hoặc setter.
- Nó có thể kiểm tra giá trị mới trước và từ chối một giá trị xấu.
- Ở dưới đây,
depositbỏ qua số tiền âm, vì vậy số dư vẫn an toàn.
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 so với instance
- Một trường instance thuộc về một đối tượng. Mỗi đối tượng đều có riêng của mình.
- Một trường
staticthuộc về lớp chính nó — nó được chia sẻ bởi tất cả các đối tượng. - Bên dưới,
counttăng lên 1 mỗi khi bất kỳRobotnào được tạo ra.
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()trả về văn bản mô tả đối tượng.- Java tự động gọi nó khi bạn in đối tượng hoặc ghép nó với
+. - Nó không nhận tham số nào và trả về một
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.
Lỗi thường gặp
- Hãy làm cho các trường là
privatevà truy cập chúng thông qua getters và setters. - Một setter có thể kiểm tra một giá trị trước khi lưu trữ nó.
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.
Bây giờ bạn thử
- Điền vào mỗi lớp để dữ liệu riêng của nó chỉ được thay đổi duy nhất thông qua các phương thức an toàn.
- Một Harness ẩn sẽ tạo đối tượng, gọi các phương thức và kiểm tra kết quả.
- Nhấn Run để biên dịch, sau đó nhấn 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. · Hoàn thiện BankAccount. Giữ cho balance là private. deposit(amount) chỉ thêm số tiền nếu nó lớn hơn 0. withdraw(amount) chỉ trừ đi nếu số tiền lớn hơn 0 và không vượt quá số dư (không được phép nợ). getBalance() trả về số dư.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Complete Temperature. The constructor stores an int degrees in a private field. toString() returns the degrees followed by C — for 21 it returns 21C. · Hoàn thiện Temperature. Constructor lưu một int degrees vào một trường private. toString() trả về số độ theo sau là C — đối với 21 nó sẽ trả về 21C.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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. · Hoàn thiện Widget. Một trường private static là count bắt đầu bằng 0. Mỗi khi một Widget được tạo ra, constructor sẽ tăng count lên 1. Phương thức static getCount() trả về số lượng widgets đã được sản xuất.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.