So you have a class with fields like brand and year. Every time
you create an object, you have to manually set those fields. That gets old fast.
That is where constructors come in. A constructor is a special method
that runs automatically when you create an object with new. Its job is to
set up the object so it is ready to use.
The Default Constructor
Here is the thing โ every Java class has a constructor even if you do not write one.
Java gives you a default constructor for free. It takes no parameters
and sets numeric fields to 0, booleans to false, and
objects to null.
public class Car {
String brand;
int year;
}
public class Main {
public static void main(String[] args) {
Car c = new Car(); // default constructor runs
System.out.println(c.brand); // null
System.out.println(c.year); // 0
}
}
See? Java initialized those fields to their default values without me writing a single line of constructor code.
Writing Your Own Constructor
But default values are rarely useful. You usually want to set your own values when creating an object. That is when you write a parameterized constructor.
public class Car {
String brand;
int year;
Car(String brand, int year) {
this.brand = brand;
this.year = year;
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car("Toyota", 2022);
System.out.println(c.brand + " " + c.year);
}
}
The constructor has the same name as the class and no return type โ not even
void. It just runs and sets things up.
The this Keyword
You probably noticed this.brand = brand in that constructor. The
this keyword refers to the current object. It is how you tell Java
"the brand that belongs to this object, not the parameter."
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void introduce() {
System.out.println("Hi, I am " + this.name);
}
}
Without this, Java would think you are assigning the parameter to itself,
which does nothing. this saves you from having to come up with different
parameter names like studentName and studentAge.