Sub topic 12
Constructors and Object Initialization
When you create an object in Java, something has to set it up. A constructor is a special method that runs automatically when an object is created. Its job is to give the new object its starting values.
In this chapter you'll learn what a constructor is, how to write one, and how the keyword this helps you avoid confusion. You should already know how to define a simple class with fields and methods, and how to create an object with new.
Why Constructors Matter
Remember the Dog class from earlier chapters? Suppose we create a dog but forget to set its name:
class Dog {
String name;
void speak() {
System.out.println(name + " says Woof!");
}
}
Dog d = new Dog();
d.speak(); // prints "null says Woof!" — not what we wantThe field name was never assigned, so Java gives it the default value null, which means "no object yet." A constructor fixes this by forcing the name to be set at creation time.
Writing a Constructor
A constructor looks like a method, but with two special rules:
- It has the same name as the class.
- It has no return type — not even
void.
class Dog {
String name;
Dog(String name) { // constructor
this.name = name; // assign the parameter to the field
}
void speak() {
System.out.println(name + " says Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Rex");
d.speak(); // prints "Rex says Woof!"
}
}When the line new Dog("Rex") runs, Java allocates memory for a new Dog object and immediately calls the constructor with "Rex". You never call the constructor by hand; new does it for you.
What `this` Means
Inside the constructor, this.name means "the name field of this object," while plain name on the right side refers to the constructor's parameter. This is needed because both are called name.
If the parameter had a different name, this would be optional:
Dog(String n) {
name = n; // no ambiguity, so this. is not required
}Many programmers still write this. anyway — it makes the intent obvious.
The Default Constructor
If you write a class with no constructor at all, Java secretly gives you one with no parameters, called the default constructor. That's why new Dog() worked in earlier chapters before we added any constructor.
Multiple Constructors (Overloading)
A class can have more than one constructor, as long as each has a different parameter list. This is called overloading:
class Dog {
String name;
Dog() {
this("Unnamed"); // call the other constructor
}
Dog(String name) {
this.name = name;
}
}
Dog a = new Dog(); // name is "Unnamed"
Dog b = new Dog("Bella"); // name is "Bella"The line this("Unnamed") calls the second constructor from the first, so the setup logic lives in one place. A call to another constructor with this(...) must be the first line in the constructor body.
Initialization Order
Here is what happens when you write new Dog("Rex"):
Fields get default values (0, false, or null) before the constructor runs, so the constructor can safely read and overwrite them.
Exercise
What is printed by this code? class Cat { String name; Cat(String name) { this.name = name; } } Cat c = new Cat("Milo"); System.out.println(c.name);
Show answer
Milo. The constructor receives "Milo", and this.name = name copies it into the object's name field.
Exercise
Why does new Dog() fail to compile after you add a constructor Dog(String name)?
Show answer
Writing any constructor removes the automatic default constructor, and no zero-argument constructor exists anymore. Add an explicit Dog() constructor to make it work.