Syntax
public ClassName(parameters) {\n // initialization code\n}Examples
Basic Constructor
Initializing fields when an object is created.
public class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void display() {
System.out.println("(" + x + ", " + y + ")");
}
}
Point p = new Point(3, 4);
p.display(); // (3, 4)Constructor Overloading
Providing multiple constructors with different parameter lists for flexibility.
public class Rectangle {
private double width, height;
public Rectangle() {
this.width = 1;
this.height = 1;
}
public Rectangle(double side) { // square shortcut
this.width = side;
this.height = side;
}
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
}
Rectangle r1 = new Rectangle(); // 1x1
Rectangle r2 = new Rectangle(5); // 5x5 square
Rectangle r3 = new Rectangle(4, 6); // 4x6Constructor Chaining with this()
Having one constructor call another in the same class to avoid duplicating initialization logic.
public class User {
private String name;
private String role;
public User(String name) {
this(name, "member"); // calls the constructor below
}
public User(String name, String role) {
this.name = name;
this.role = role;
}
public void display() {
System.out.println(name + " (" + role + ")");
}
}
User u1 = new User("John"); // John (member)
User u2 = new User("Zain", "admin"); // Zain (admin)The Default Constructor
Java provides a no-argument constructor automatically, but only if you don't define any constructor yourself.
public class Simple {
private int value;
// No constructor written - Java provides a default no-arg one automatically
}
Simple s = new Simple(); // works fine, uses default constructor
public class WithConstructor {
private int value;
public WithConstructor(int value) { // once you write ANY constructor...
this.value = value;
}
}
// WithConstructor w = new WithConstructor(); // Error! default constructor no longer existsBest practices
- Use this(...) to chain constructors and avoid duplicating initialization logic across multiple overloads
- Remember that defining any constructor removes the automatically provided no-argument default constructor
- Validate arguments inside constructors (e.g. throwing an exception for invalid values) to prevent objects from ever existing in an invalid state
- Keep constructors focused on initialization - avoid putting complex business logic inside them
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification