What Is a Constructor in Java?
A constructor is a special method that runs automatically when you create an object with new. Its job is to initialise the object's state. It has the same name as the class and no return type.
Basic example
public class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
}
Person p = new Person("Ada", 36);
System.out.println(p.getName()); // Ada
Default constructor
If you declare no constructors at all, Java silently adds a no-argument default constructor that does nothing:
public class Empty {}
Empty e = new Empty(); // works, Java added Empty() {} for you
The moment you declare any constructor, the default constructor disappears. If you still need a no-arg constructor, declare it explicitly.
Overloaded constructors
public class Product {
private String name;
private double price;
private int stock;
public Product(String name, double price) {
this(name, price, 0); // delegates to the 3-arg constructor
}
public Product(String name, double price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
}
this(...) is constructor chaining — it calls another constructor in the same class and must be the first statement.
this keyword in constructors
this.name = name; — when the parameter name shadows the field name, this. disambiguates: it refers to the current object's field, not the parameter.
Constructor vs method
| Constructor | Method | |
|---|---|---|
| Name | Same as the class | Any name |
| Return type | None (not even void) | Any type or void |
| Called by | new keyword | Dot notation on an object |
| Purpose | Initialise object state | Perform operations |
Constructors and inheritance
The first line of every subclass constructor implicitly calls super() (the parent's no-arg constructor) unless you explicitly call super(...) with arguments. If the parent has no no-arg constructor, you must call the right super() explicitly.
public class Animal {
protected String sound;
public Animal(String sound) { this.sound = sound; }
}
public class Dog extends Animal {
public Dog() {
super("Woof"); // must call Animal's constructor
}
}
Immutable objects
A constructor-only init pattern (with final fields and no setters) creates immutable objects — safe to share across threads with no synchronisation:
public final class Money {
private final long cents;
private final String currency;
public Money(long cents, String currency) {
this.cents = cents;
this.currency = currency;
}
public long getCents() { return cents; }
public String getCurrency() { return currency; }
}