Constructors in Java - Types of Constructors [With Examples]
A constructor in Java is a special block of code, similar to a method, that is automatically called when an object of a class is created. It's used to initialize the object's fields.
Rules for Writing a Constructor
- The constructor name must exactly match the class name
- A constructor has no return type, not even
void - A constructor is invoked automatically using the
newkeyword
Types of Constructors
1. Default Constructor
If you don't define any constructor, Java automatically provides a default, no-argument constructor that initializes fields with default values.
class Student {
String name;
int age;
// Java provides: Student() { }
}
2. No-Argument Constructor
A constructor you write yourself that takes no parameters but contains custom initialization code.
class Student {
String name;
Student() {
name = "Unknown";
}
}
3. Parameterized Constructor
A constructor that accepts arguments to initialize fields with specific values at creation time.
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Why Constructors Matter
- They guarantee an object starts in a valid, properly initialized state
- They remove the need to call a separate "init" method after creating an object
- They support overloading, letting objects be created in multiple ways
super().Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.
Constructor Chaining With this() and super()
When a class has several constructors, repeating the same assignments in each one invites mistakes. Chaining lets one constructor call another so the real setup happens in a single place.
class Account {
String holder;
double balance;
String type;
Account(String holder) {
this(holder, 0.0); // delegate to the two-argument version
}
Account(String holder, double balance) {
this(holder, balance, "SAVINGS");
}
Account(String holder, double balance, String type) {
this.holder = holder;
this.balance = balance;
this.type = type;
}
}
Account a = new Account("Neha"); // balance 0.0, type SAVINGS
Calls to this(...) or super(...) have traditionally had to be the first statement in a constructor, and you can use only one of them. Recent Java releases relax this a little by allowing simple statements before the call as long as they do not use the object being built, but keeping the call first remains the clearest style.
Two More Constructor Patterns
Copy constructor
Java has no automatic copy constructor, but you can write one that builds a new object from an existing one. This is handy when you want an independent duplicate rather than a second reference to the same object.
class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
Point(Point other) { this(other.x, other.y); }
}
Point p1 = new Point(2, 3);
Point p2 = new Point(p1);
p2.x = 10; // p1.x is still 2
Private constructor
Marking a constructor private stops other classes from calling new. Utility classes full of static methods use it to prevent pointless objects, and the singleton pattern uses it so the class controls its single instance through a static method.
Worked Example: Order of Execution
Understanding the order in which code runs explains many surprising outputs in interviews.
class Parent {
Parent() { System.out.println("1. Parent constructor"); }
}
class Child extends Parent {
static { System.out.println("0. Child static block"); }
{ System.out.println("2. Child instance block"); }
Child() {
super();
System.out.println("3. Child constructor");
}
}
new Child();
The static block runs once when the class is loaded. Then the parent constructor finishes, then instance initializer blocks and field initializers run, and finally the rest of the child constructor executes. If you leave out super(), the compiler inserts a call to the parent's no-argument constructor for you.
Mistakes Beginners Make With Constructors
- Adding a return type. Writing
void Student()creates an ordinary method with the class name, and the class quietly falls back to the default constructor. - Losing the default constructor. As soon as you write any constructor, Java stops generating the no-argument one, so
new Student()fails to compile unless you add it. - Forgetting
this. Writingname = name;assigns the parameter to itself and leaves the field empty. - Parent without a no-argument constructor. A subclass must then call
super(...)with suitable arguments explicitly. - Calling overridable methods inside a constructor. The subclass version may run before the subclass fields are set, which leads to null values.
- Doing heavy work. Opening files or network connections in a constructor makes objects slow and hard to test; prefer passing ready dependencies in.
Rule of thumb: a constructor should leave the object valid and do little else. Validation of arguments, for example throwing IllegalArgumentException for a negative balance, fits well; long-running logic does not.