Constructors
Prerequisites: Introduction to classes & objects
A constructor initializes an object's fields at the moment it's
created with new — it shares the class's name and has no return
type.
class Dog {
String name;
int age;
Dog(String name, int age) {
this.name = name;
this.age = age;
}
}
Dog rex = new Dog("Rex", 3);
this.name refers to the field on the object being constructed,
distinguishing it from the constructor parameter of the same name.
Common mistakes
- Omitting
this.when a parameter shadows a field of the same name —name = name;just assigns the parameter to itself and never touches the field. - Forgetting that once you define any constructor, Java stops generating the free no-argument constructor automatically.