+91 81900 98289

Java Constructors

A constructor has the class name and no return type. Its job is to leave the new object in a valid state. Require the values you cannot do without, such as a student name, as parameters.

You can overload constructors. One can take a name, and another can take a name and a batch. this(name) from the second constructor calls the first and avoids copying the assignment lines.

Example

The constructor stores Weekday on the object. main then prints that field.

public class Batch { String name; Batch(String name) { this.name = name; } public static void main(String[] args) { Batch b = new Batch("Weekday"); System.out.println(b.name); } }
If the parameter and the field share a name, this.name is the field and name is the parameter. Without this, the parameter is assigned to itself and the field stays null.