The Plain Picture#
When a new house is handed over, it shouldn't be an empty shell you finish yourself. The builder asks, "Which colour? How many bedrooms?" and hands you a house that's ready to live in.
The Real Names#
A constructor is special code that runs when an object is created with
new, to set it up. It has the same name as the class and no return type.thismeans "the object currently being set up / used". It's how you tell a field apart from a parameter with the same name.
Under the Hood#
class Student {
String name;
int score;
Student(String name, int score) {
// constructor: same name as the class, no return type
this.name = name; // this.name = the FIELD; name = the PARAMETER
this.score = score;
}
Student(String name) {
// an overloaded constructor (01_java_basics.md Ch 7)
this(name, 0); // call the other constructor: "constructor chaining"
}
}Student priya = new Student("Priya", 180);
Student rahul = new Student("Rahul"); // score starts at 0What new Student("Priya", 180) does, step by step:
Finds room on the heap (Operating Systems Ch 6) for a new
Studentobject.Sets every field to its default (
null,0).Runs the constructor, which assigns
"Priya"and180.Gives back a reference to the new object, stored in
priya(Ch 4).
The default constructor: if you write no constructor at all, Java quietly adds an empty one with no parameters — that's why
new Student() worked in Chapter 1. The moment you write any constructor, that free one disappears.
this(...) must be the first line in a constructor, and lets one constructor reuse another so the setup logic lives in one place.
Gotchas
Forgetting
this.—name = name;assigns the parameter to itself; the field staysnull. The compiler won't complain.Putting a return type on a constructor —
void Student(String name)is silently a normal method namedStudent, not a constructor.
Check yourself
4 questionsHow do you recognise a constructor?
Show answerHide answer
Same name as the class, no return type; it runs on new.
What does this.name = name; mean?
Show answerHide answer
Assign the parameter name to the current object's field name.
You wrote Student(String name). Why does new Student() no longer compile?
Show answerHide answer
Writing any constructor removes the automatic no-argument default constructor.
What does this(name, 0) do?
Show answerHide answer
Calls the class's other constructor (with two parameters) from this one.