Encapsulation: private fields, 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.
Защита данных
- Инкапсуляция означает сокрытие данных объекта и изменение их только через методы.
- Это сохраняет данные в безопасности. Другой код не может присвоить им недопустимое значение.
- Основные инструменты — слова
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().
Аксессоры (геттеры)
- Поле является приватным, поэтому мы добавляем метод
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 экземпляр
- Поле экземпляра принадлежит одному объекту. У каждого объекта есть свое.
- Поле
staticпринадлежит самому классу — оно общее для всех объектов. - Ниже,
countувеличивается на 1 каждый раз, когда создается любойRobot.
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.
Теперь попробуйте сами
- Заполните каждый класс так, чтобы его приватные данные изменялись только через безопасные методы.
- Скрытый 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.
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.
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.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.