-
Notifications
You must be signed in to change notification settings - Fork 137
Java Constructors
A complete guide to understanding Java constructors from beginner to advanced level.
- What is a Constructor?
- Why Do We Need Constructors?
- How Object Creation Works in Java
- Constructor Rules
- Types of Constructors
- Default Constructor
- No-Argument Constructor
- Parameterized Constructor
- Constructor Overloading
- Using
thisKeyword in Constructors - Constructor Chaining
- Using
super()in Constructors - Constructor Execution Order
- Constructors and Inheritance
- Constructor Access Modifiers
- Private Constructors
- Copy Constructor in Java
- Constructor vs Method
- Initialization Blocks vs Constructors
- Common Constructor Mistakes
- Best Practices
- Real-World Examples
- Interview Questions
- Final Summary
A constructor is a special member of a class that is used to initialize objects.
A constructor is automatically executed when an object is created using the new keyword.
Example:
class Student {
String name;
Student() {
name = "Unknown";
}
}Creating an object:
Student student = new Student();When the object is created, Java automatically calls:
Student()Without constructors, object initialization becomes repetitive.
Example without constructor:
class Student {
String name;
int age;
}Creating objects:
Student s1 = new Student();
s1.name = "John";
s1.age = 20;Every object requires manual initialization.
With a constructor:
class Student {
String name;
int age;
Student(String name, int age){
this.name = name;
this.age = age;
}
}Now:
Student s1 = new Student("John",20);The object is created with valid data immediately.
When Java executes:
Student s = new Student();The JVM performs:
1. Allocate memory for object
↓
2. Initialize variables with default values
↓
3. Execute constructor
↓
4. Return object reference
Example:
class Student {
String name;
int age;
Student(){
name = "Alice";
age = 20;
}
}Before constructor:
name = null
age = 0
After constructor:
name = Alice
age = 20
A constructor must follow these rules:
Correct:
class Student {
Student(){
}
}Wrong:
class Student {
student(){
}
}Correct:
Student(){
}Wrong:
void Student(){
}The second one is a method, not a constructor.
You cannot call it like a normal method.
Wrong:
Student();Correct:
new Student();A class can have multiple constructors.
Constructors belong to object creation, not inheritance.
Java has three commonly used constructor types:
| Type | Description |
|---|---|
| Default Constructor | Created automatically by compiler |
| No-Argument Constructor | Programmer-created constructor without parameters |
| Parameterized Constructor | Constructor that accepts values |
A default constructor is automatically created by Java if no constructor is written.
Example:
class Student {
}Compiler creates:
Student(){
}Now:
Student s = new Student();works correctly.
If you create any constructor, Java will not create a default constructor.
Example:
class Student {
Student(String name){
}
}Now:
Student s = new Student();causes:
Compile Error
A no-argument constructor is a constructor without parameters.
Example:
class Student {
String name;
Student(){
name = "Unknown";
}
}Usage:
Student s = new Student();A parameterized constructor accepts values.
Example:
class Student {
String name;
int age;
Student(String name, int age){
this.name = name;
this.age = age;
}
}Usage:
Student s = new Student("John",21);Object state:
name = John
age = 21
Constructor overloading means having multiple constructors with different parameters.
Example:
class Student {
Student(){
}
Student(String name){
}
Student(String name, int age){
}
}Java decides which constructor to call based on arguments.
Example:
new Student();
new Student("John");
new Student("John",20);this refers to the current object.
It is commonly used to differentiate instance variables and constructor parameters.
Example:
class Student {
String name;
Student(String name){
this.name = name;
}
}Without this:
name = name;Both refer to the parameter.
With this:
this.namemeans object variable.
Constructor chaining means calling one constructor from another constructor.
It avoids duplicate code.
Example:
class Student {
Student(){
this("Unknown");
}
Student(String name){
System.out.println(name);
}
}Execution:
Student()
↓
Student(String)
↓
Print name
- Must be the first statement.
- Can only call another constructor in the same class.
- Cannot call multiple constructors.
Example:
Student(){
this("John");
System.out.println("Hello");
}Valid.
super() calls the parent class constructor.
Example:
class Animal {
Animal(){
System.out.println("Animal Constructor");
}
}
class Dog extends Animal {
Dog(){
super();
System.out.println("Dog Constructor");
}
}Output:
Animal Constructor
Dog Constructor
In inheritance, parent constructors execute before child constructors.
Example:
class A {
A(){
System.out.println("A");
}
}
class B extends A {
B(){
System.out.println("B");
}
}
class C extends B {
C(){
System.out.println("C");
}
}Creating:
new C();Output:
A
B
C
Order:
Parent
↓
Child
↓
Grand Child
Constructors are not inherited.
Example:
class Parent {
Parent(){
}
}
class Child extends Parent {
}Child does not inherit the constructor.
Instead, Java automatically calls:
super();Constructors can have access modifiers.
Accessible everywhere.
public Student(){
}Accessible in subclasses and same package.
protected Student(){
}No modifier.
Student(){
}Accessible only inside the class.
private Student(){
}Private constructors prevent object creation from outside the class.
Common uses:
- Singleton Pattern
- Utility Classes
- Factory Pattern
Example:
class Database {
private Database(){
}
}Now:
new Database();is impossible.
class Database {
private static Database instance;
private Database(){
}
public static Database getInstance(){
if(instance == null){
instance = new Database();
}
return instance;
}
}Only one object can exist.
Java does not provide built-in copy constructors.
But we can create our own.
Example:
class Student {
String name;
Student(String name){
this.name = name;
}
Student(Student other){
this.name = other.name;
}
}Usage:
Student s1 = new Student("John");
Student s2 = new Student(s1);| Constructor | Method |
|---|---|
| Initializes objects | Performs operations |
| Same name as class | Any valid name |
| No return type | Has return type |
| Called automatically | Called manually |
| Cannot be overridden | Can be overridden |
| Runs during object creation | Runs when called |
Java initialization block:
class Student {
{
System.out.println("Initialization Block");
}
Student(){
System.out.println("Constructor");
}
}Execution:
Initialization Block
↓
Constructor
Wrong:
void Student(){
}Correct:
Student(){
}Wrong:
student(){
}Correct:
Student(){
}Wrong:
Student(){
System.out.println("Hello");
this("John");
}this() must be the first statement.
Too many constructors make classes difficult to maintain.
Good:
Student(String name){
this.name=name;
}Example:
Student(int age){
if(age < 0){
throw new IllegalArgumentException();
}
}Avoid:
- Database calls
- Network calls
- Heavy calculations
Example:
class Student {
private final int id;
Student(int id){
this.id=id;
}
}class User {
private String username;
private String email;
User(String username,String email){
this.username=username;
this.email=email;
}
}class BankAccount {
private String accountNumber;
private double balance;
BankAccount(String accountNumber,double balance){
this.accountNumber = accountNumber;
this.balance = balance;
}
}class Product {
String name;
double price;
Product(String name,double price){
this.name=name;
this.price=price;
}
}| Concept | Description |
|---|---|
| Constructor | Initializes objects |
| Same name as class | Required |
| Return type | Not allowed |
| Called automatically | Yes |
| Default constructor | Compiler generated |
| Parameterized constructor | Initializes with values |
| Overloading | Multiple constructors |
this() |
Calls another constructor |
super() |
Calls parent constructor |
| Inherited | No |
| Overridden | No |
| Private constructors | Used for Singleton and utility classes |
| Best practice | Keep constructors simple |
- Constructors are responsible for creating valid objects.
- Every Java object creation involves constructor execution.
- Use parameterized constructors to initialize required values.
- Use
this()for constructor reuse inside a class. - Use
super()when working with inheritance. - Constructors are not methods and follow different rules.
- Good constructor design improves code readability, safety, and maintainability.