Constructores
Introducido| English | Significado |
|---|---|
| default constructor/dɪˈfɒlt kənˈstrʌktə/ | constructor por defecto |
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.
Dos ejecuciones de new Student("Ada") se refieren al mismo objeto porque los argumentos son iguales.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Cada expresión new exitosa construye un objeto distinto; que los argumentos sean iguales no hace que las referencias sean iguales.
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.
Los constructores establecen el estado inicial
Cada nuevo objeto se configura mediante los argumentos del constructor.
Un constructor tiene...
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Mismo nombre que la clase, sin tipo de retorno — ni siquiera void.
¿Cuándo se ejecuta un constructor?
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
new invoca el constructor para construir el objeto.
Si no escribes ningún constructor, Java proporciona un constructor por defecto sin argumentos.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Pero escribir cualquier constructor elimina ese default gratuito.
Una vez que defines un constructor con parámetros, new Student() sigue funcionando automáticamente.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
El default gratuito ha desaparecido; escribe un constructor sin argumentos si lo necesitas.
Escribir dos constructores con diferentes listas de parámetros es un ejemplo de...
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Mismo nombre, diferentes parámetros = sobrecarga.
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").
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
The supplied argument selects a matching constructor; declaring it does not also create a no-argument constructor.
Un Counter tiene private int value = 7; y un constructor explícito que luego asigna value = 9;. ¿Cuál es el valor de value inmediatamente después de la construcción?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
El inicializador del campo asigna 7 antes de que el cuerpo del constructor asigne 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.