Constructors
| English | Chinese | Pinyin |
|---|---|---|
| default constructor | 默认构造函数 | mò rèn gòu zào hán shù |
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 even
void). 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. - Different arguments → different objects, each configured at birth.
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.
The default constructor
- If you write no constructor, Java provides a hidden default constructor 默认构造函数 with no parameters.
- It sets number fields to
0, booleans tofalse, and object references tonull. - 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.
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.
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.
Constructors set the starting state
Each new object is configured by the constructor's arguments.
A constructor has...
Same name as the class, no return type — not even void.
When does a constructor run?
new invokes the constructor to build the object.
If you write no constructor, Java provides a default no-argument constructor.
But writing any constructor removes that free default.
Once you define a constructor with parameters, new Student() still works automatically.
The free default is gone; write a no-arg constructor if you need one.
Writing two constructors with different parameter lists is an example of...
Same name, different parameters = overloading.