Конструкторы
Введено
7:25
Создание классов
Вот студент, хранящийся как три отдельных переменных: имя, курс и оценка. Это работает. Теперь добавьте тысячу студентов. Вам понадобятся три тысячи переменных…
Озвучивание на английском · переключаемые субтитры на английском и китайском языках
В этом уроке
| English | Значение |
|---|---|
| default constructor/dɪˈfɒlt kənˈstrʌktə/ | Конструктор по умолчанию |
A parameterised constructor does not supply a no-arg one
- Student declares only Student(String n). Creating new Student("Ada") works, but new Student() has no matching constructor.
- Java supplies an implicit default constructor only when none is declared. To allow both calls, explicitly write Student() and Student(String n).

Setting up a new object
- A constructor runs when an object is created with
new, to set its initial state. It has the same name as the class and no return type (not evenvoid). public Student(String n) { name = n; score = 0; }Its job: give the brand-new object sensible starting values.
Constructor parameters
- Parameters let each new object start with its own values.
new Student("Ada")passes"Ada"to the constructor'snparameter. - Inside,
name = n;copies the argument into the instance variable. Each successfulnewexpression creates a distinct object, even when its arguments are identical. Different arguments need not produce different field values if the constructor ignores or normalizes them.
Два вызова new Student("Ada") ссылаются на один и тот же объект, потому что аргументы равны.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Каждый успешный вызов оператора new конструирует отдельный объект; равные аргументы не делают ссылки равными.
Overloading constructors
- A class can have several constructors with different parameter lists — overloading.
Student(String n)andStudent(String n, int s)are both valid. - Java picks the one whose parameters match your
newarguments. This offers callers flexible ways to build an object.
Конструкторы устанавливают начальное состояние
Каждый новый объект конфигурируется аргументами конструктора.
У конструктора есть...
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
То же имя, что и у класса, нет типа возвращаемого значения — даже void.
Когда выполняется конструктор?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
new вызывает конструктор для создания объекта.
Если вы не пишете конструктор, Java предоставляет конструктор по умолчанию без параметров.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Но написание любого конструктора удаляет эту бесплатную версию по умолчанию.
Как только вы определяете конструктор с параметрами, new Student() все еще работает автоматически.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Бесплатная версия по умолчанию исчезла; напишите конструктор без параметров, если он вам нужен.
Написание двух конструкторов с разными списками параметров является примером...
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Одно имя, разные параметры = перегрузка.
The default constructor
- If you write no constructor, Java provides a hidden default constructor 默认构造函数 with no parameters. Fields first have default values (
0,false,null); explicit field initialisers can then set other initial values. - But once you write any constructor, that free default disappears. So if you need a no-arg constructor and a parameterized one, write both.
A constructor has the class's name and NO return type — writing void makes it an ordinary method, not a constructor. And once you define any constructor, Java stops giving you the free no-argument default; if you still want new Student(), you must write that constructor yourself.
Order the steps used to evaluate new Student("Ada").
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
The supplied argument selects a matching constructor; declaring it does not also create a no-argument constructor.
У Counter есть приватное поле int value = 7; и явный конструктор, который затем присваивает value = 9;. Каково значение value непосредственно после создания?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Инициализатор поля присваивает 7 до того, как тело конструктора присваивает 9.
Two constructors for Student:
public Student(String n) { name = n; score = 0; }public Student(String n, int s) { name = n; score = s; }new Student("Ada")→ score0;new Student("Bo", 75)→ score75.
Carry the reasoning to a new case
- Compare
class Counter { private int value = 7; }with an otherwise identical class whose explicit constructor assignsvalue = 9;. The first starts at 7 after its field initializer; the second ends construction at 9. - Fields receive default values before field initializers and the constructor body run. A programmer-written no-argument constructor is not the compiler-supplied default constructor, even though both take no arguments.
A constructor (same name as the class, no return type) runs on new to set an object's initial state, using parameters for per-object values. A class can overload several constructors. Write no constructor and Java supplies a default no-arg one — but defining any constructor removes that free default.
Что пошло не так? Это увидит только команда сайта.