Back to Study Material Java

Constructors in Java

A constructor is a special method that runs automatically when an object is created with new. Its job is to initialize the object's fields to a valid start...

Constructors in Java

Initializing Objects with Constructors

A constructor is a special method that runs automatically when an object is created with new. Its job is to initialize the object's fields to a valid starting state. Constructors look like methods but have two distinctive features: they share the exact name of the class, and they have no return type—not even void. Every class has at least one constructor; if you write none, the Java compiler silently provides a default no-argument constructor.

Types of Constructors A no-argument (default) constructor initializes fields to defaults. A parameterized constructor accepts values and uses them to set fields immediately at creation. Java does not copy constructors by default as C++ does, but you can write one manually: a constructor that takes an instance of the same class and copies its fields. A private constructor prevents instantiation from outside the class, which is the foundation of the Singleton design pattern.

Constructor Chaining Constructors can call other constructors in the same class using this() as the first statement. This avoids duplicating initialization logic across overloaded constructors. A constructor can also call a parent class constructor using super() as the first statement, ensuring the parent's initialization runs before any child-specific setup. If you do not explicitly call super(), Java inserts super() automatically, which calls the parent's no-argument constructor.

Constructors vs Methods Constructors run only once per object, at creation time. Methods can be called any number of times. Constructors cannot be inherited or overridden—a subclass does not inherit parent constructors, though it can call them via super(). Constructors cannot be abstract, static, final, or synchronized. These restrictions make sense because a constructor is part of the creation process, not the object's runtime behavior.

Code Example: class Point { int x, y; Point() { this(0, 0); } // chains to parameterized Point(int x, int y) { this.x = x; this.y = y; } } Point origin = new Point(); // uses no-arg, x=0 y=0 Point p = new Point(3, 4); // x=3 y=4

Interview Tip: Interviewers often ask what happens if you define a parameterized constructor but no no-argument constructor. The compiler does not generate the default no-argument constructor, so any code trying to call new ClassName() will fail to compile. This surprises many developers who forget that the compiler's free no-argument constructor disappears the moment any explicit constructor is written.