Анатомия класса
Введено| English | Значение |
|---|---|
| encapsulation/ɪnˌkæpsjʊˈleɪʃn/ | Инкапсуляция |
| instance variables/ˈɪnstəns ˈveərɪəblz/ | Переменные экземпляра |
Private fields still need checked methods
- A Student has a private score, but
public void setScore(int s) { score = s; }still lets a caller supply -5. Private access alone does not enforce a non-negative score. - A guarded setter can reject that update. Check the constructor and every other method that writes the field too; encapsulation makes a validation policy easier to enforce but does not create it automatically.
Деление поля score приватным автоматически отклоняет отрицательные аргументы, переданные unprotected публичному сеттеру.
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
Ложь: сеттер является кодом класса и может присвоить отрицательное значение. Валидация должна быть реализована.
The three parts of a class
- The class designs here contain instance fields for data, constructors for initial setup, and methods for behavior. These are three useful parts to identify; formally, Java does not classify constructors as class members.
- Trace a Student from construction to an update: the constructor initializes its score field, and an instance method later reads or changes that object's score. A static method instead has no implicit current object.

A class diagram: private attributes and public methods
Instance variables hold state
- Instance variables 实例变量 store each object's own state.
private String name; private int score;— declared inside the class, outside any method.- Every object gets its own copy — one student's
scoreis separate from another's. - These persist for the life of the object (unlike local variables).
private and public
- Access modifiers control who can reach a member.
private— usable only inside the class;public— exposed to other code that can access the class.- Instance variables are usually
private; methods that form the interface arepublic. - This hiding of internal data is called encapsulation 封装.
Какие три части организуют проектирование класса Student, изучаемое здесь?
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
Экземплярные поля хранят состояние, конструкторы инициализируют новые объекты, а методы обеспечивают поведение. Конструкторы не являются формальными членами класса в терминологии Java.
Экземплярные переменные обычно объявляются...
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
Приватные данные + публичные методы = инкапсуляция.
Сохранение данных приватными и их предоставление только через методы называется ___ (одно слово).
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
Инкапсуляция защищает данные объекта.
Два объекта одного класса разделяют одну копию каждой экземплярной переменной.
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
У каждого объекта есть своя копия экземплярных переменных.
Для представленного здесь корневого класса Student сторонний внешний класс может напрямую читать приватное поле...
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
Приватный доступ запрещает внешнему не связанному классу напрямую читать поле. Код внутри класса Student может прочитать приватное поле другого объекта Student.
Why keep data private
- Encapsulation prevents unrelated external code from directly assigning a private field. Code inside Student can still read or write private fields, including those of another explicitly referenced Student.
- Outsiders interact only through public methods, which can validate and control access.
- You could reject a negative score in a method; a public variable has no such guard.
- Private fields with a deliberately chosen public interface support controlled updates. Each method and constructor must still implement the intended rules; returning a mutable internal object can also expose changes indirectly.
Keep instance variables private; expose behavior through public methods. A public field lets any code set it to anything (a negative score, a null name) with no checks. Encapsulation funnels all access through methods that can validate the change. Each object has separate instance-field storage, but reference fields in different objects may point to the same shared object. Distinguish separate fields from separate referenced objects.
Два объекта имеют отдельные поля ссылок, поэтому эти поля должны указывать на разные объекты.
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
Ложь: отдельные поля ссылок могут оба указывать на один и тот же изменяемый объект.
Два студента ссылаются на одну и ту же изначально пустую ArrayList. Один добавляет один элемент. Какой размер списка наблюдает другая ссылка?
Сложность 2/5 · 140 монет + небольшой бонус за первое выполнение сегодня
Обе ссылки указывают на один и тот же объект списка, размер которого теперь равен 1.
Anatomy of a Student class:
- Instance variables:
private String name; private int score; - Constructor:
public Student(String n) { ... } - Methods:
public void addScore(int s) { ... },public int getScore() { ... }
Separate field storage from shared objects
- If two Student objects both store a reference to the same ArrayList, their list fields are separate but the referenced list is shared. Adding an item through either reference changes that one list.
- Reassigning one student's list field to a new ArrayList changes only that field. Follow reference arrows when predicting state; private access and object identity answer different questions.
A class has instance variables (each object's state), constructors (set up new objects), and methods (behaviors). Instance variables are usually private and accessed through public methods — this encapsulation protects the data. Each object holds separate instance fields; the objects referenced by those fields may still be shared.
У каждого объекта свое состояние
a.score и b.score — это разные переменные; каждый объект владеет своим состоянием.