Классовые переменные и методы
Введено
7:25
Создание классов
Вот студент, хранящийся как три отдельных переменных: имя, курс и оценка. Это работает. Теперь добавьте тысячу студентов. Вам понадобятся три тысячи переменных…
Озвучивание на английском · переключаемые субтитры на английском и китайском языках
В этом уроке
| English | Значение |
|---|---|
| static variable/ˈstætɪk ˈveərɪəbl/ | Статическая переменная |
| static method/ˈstætɪk ˈmeθəd/ | статический метод |
Two objects, one construction count
- Ada and Bo have separate scores, but creating either student increases the same static variable 静态变量,
Student.count. After two constructions, the count is 2; changing Ada's score does not change Bo's score. - Compare what each value describes: a score describes one student, while this counter describes constructions of the class. A copied reference to Ada creates no new object and does not increment the counter.

Put each field at the right level
- An instance field has a separate storage location in each object. A static field has one storage location for this loaded class, even before any objects are constructed;
privatecontrols access, not the number of copies. - In this small single-threaded example, the constructor increases
countonce per construction. It counts objects constructed, not objects still alive: losing a reference does not automatically decrease it.
class Student {
private int score;
private static int count = 0;
public Student(int initialScore) {
score = initialScore;
count++;
}
public int getScore() { return score; }
public void setScore(int newScore) { score = newScore; }
public static int getCount() { return count; }
public static int readScore(Student s) { return s.score; }
}
Одна общая статическая переменная count
count — это общее значение, принадлежащее классу.
Статическая (классовая) переменная — это...
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
static означает один общий экземпляр, принадлежащий классу.
Если конструктор выполняет count++ и count изначально равен 0, чему будет равно count после создания 3 объектов?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Каждая конструкция увеличивает общую переменную count → 3.
A static method has no receiver
- A static method 静态方法 has no implicit current object, so it cannot use
thisor an unqualified instance field such asscore.getCount()can readcountbecause that field belongs to the class. - Static does not forbid working with objects.
readScore(Student s)receives an explicit object reference and readss.score; it is insideStudent, where access to that private field is allowed. Heresmust be non-null.
return score; inside a static method is a compile-time error in this class. return s.score; inside the shown static method is valid: the reference identifies which student's score to read.
Внутри показанного класса Student статический метод может использовать return score; без указания какого-либо объекта Student.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Ложь: score — это поле экземпляра, а этот статический метод не имеет неявного получателя. При наличии параметра non-null Student s, return s.score; допустим внутри класса Student.
Внутри класса Student какой статический метод может прочитать оценку параметра s (non-null)?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Явная ссылка s идентифицирует объект; сам класс Student может получить доступ к своему приватному полю score.
Trace class and object calls
- After
Student a = new Student(50);andStudent b = new Student(75);,Student.getCount()is 2,a.getScore()is 50 andb.getScore()is 75.a.setScore(60)changes only Ada's score. Student.readScore(a)then returns 60 without constructing another student. The method is static, yet its explicit parameter identifies an existing object whose state it reads.
Инстансный метод, такой как getScore(), вызывается на...
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Инстансные члены работают с конкретным объектом.
Separate legal syntax from clear style
- Prefer
Student.getCount()to show that the method belongs to the class. Java also permitsa.getCount()for this static method; that syntax does not make the count specific to Ada. a.getScore()is an instance call with Ada as its receiver.Student.getScore()is invalid here because the method needs an object and is not static; choose field and method kinds from their responsibilities.
Какой вызов лучше всего демонстрирует, что getCount() является статическим методом класса Student?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Student.getCount() явно называет класс. Java также допускает student.getCount() для статического метода, но такое написание скрывает его принадлежность к уровню класса.
Predict a reference copy
- Starting with the two constructed students,
Student alias = a;leaves the construction count at 2.alias.setScore(90)changes Ada's existing object, soa.getScore()is 90 and Bo's score remains 75. - Count executions of
new Student(...), then trace each object's state separately. Neither an accessor call nor a reference assignment creates a student, and a static method may still read an explicitly supplied object.
Static fields store class state; instance fields store object state. Static methods have no this, but may use explicit object references. Prefer class-qualified static calls and distinguish construction counts from live-object counts.
Два студента были созданы, поэтому count равен 2. Затем выполняется Student alias = a; и alias.setScore(90);. Чему равно значение Student.getCount()?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Ни присвоение ссылки, ни изменение оценки не вызывают конструктор. Значение count остается 2.
Этот счетчик конструкторов автоматически уменьшается, когда теряется ссылка на студента.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Только код, изменяющий count, меняет его. Этот пример подсчитывает создание объектов и не предоставляет декремента.
Что пошло не так? Это увидит только команда сайта.