Setting up an object straight away
Setting each field one by one is tiring. A constructor is a special method that runs automatically when you write new. It has the same name as the class and no return type:
class Student {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
void show() {
System.out.println(name + " scored " + marks);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Asha", 91);
Student s2 = new Student("Ravi", 78);
s1.show();
s2.show();
}
}Output
Asha scored 91 Ravi scored 78
What does this mean?
Inside the constructor, the parameter name and the field name have the same name. this.name means “the field of this object”, and plain name means the parameter.
Think of it like this: If everyone in a room is called “Ravi”, saying “my bag” makes it clear whose bag you mean.
thisis the object saying “my”.
More than one constructor
Constructors can be overloaded too, so there are different ways to build an object:
class Box {
int width;
int height;
Box(int width, int height) {
this.width = width;
this.height = height;
}
Box(int side) {
this(side, side);
}
int area() {
return width * height;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Box(3, 4).area());
System.out.println(new Box(5).area());
}
}Output
12 25
this(side, side) calls the other constructor, so we don't repeat code.
Remember: If you write no constructor, Java gives you an empty one for free. Once you write your own, the free one disappears.