Constructors in Java
A constructor is a special method, sharing its class's exact name and having no return type at all, not even void, that runs automatically whenever an object is created with new — its job is to initialize that new object's fields to a sensible starting state. If a class defines no constructor at all, Java silently supplies a default one that takes no arguments and does nothing beyond the automatic field defaults; the moment a class defines any constructor of its own, that free default one disappears entirely.
Constructors can be overloaded just like ordinary methods, letting objects be created several different ways. And this(...), called as the very first line of one constructor, can delegate to another constructor in the same class to avoid repeating the same initialization logic.
Matching the class name
A constructor's name must be identical to its class's name, with no return type, not even void.
Running automatically
new ClassName(...) always calls a matching constructor, initializing the object's fields as part of creation.
The implicit default constructor
A class with no constructors of its own gets a free, no-argument, do-nothing one automatically.
That default disappears once any constructor is written
Defining even one constructor removes the automatically-supplied no-argument one.
Constructor overloading and this(...)
Multiple constructors can coexist with different parameter lists, and this(...) as a constructor's first line delegates to another constructor in the same class.
public class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } Point() { this(0, 0); } public static void main(String[] args) { Point p1 = new Point(3, 4); Point p2 = new Point(); System.out.println(p1.x + "," + p1.y); System.out.println(p2.x + "," + p2.y); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.