What is Constructor in Java

A constructor in Java is a special type of method that is used to initialize the state of an object, assign default values, and perform any essential setup operations. It is automatically called when you create an instance (or an object) of a class.

Unlike regular methods, constructors have the same name as the class and do not have a return type, not even void. In object-oriented programming language, Java constructors play a significant role by setting up initial values and ensuring proper object initialization before use.

Syntax of a Constructor in Java

The basic syntax to create a constructor in Java programming is given below:

public class ClassName {
 // Constructor definition.
    ClassName() {
        // Initialization code
    }
}

In the above syntax of constructor, ClassName represents the name of the class which must match the constructor’s name. It has no return type, not even void. The constructor is called automatically in Java when an object of the class is created.

Learn constructor in Java: The ultimate guide with examples.

Example 1: Simple Constructor

// Create a class named Car.
public class Car {
    String model; // Instance variable

 // Create a constructor.
    Car() {
        model = "Tesla";
    }
public static void main(String[] args) {
// Create an object of class Car.
   Car myCar = new Car(); // Constructor called.
   System.out.println("Model: " + myCar.model);
  }
}
Output: 
     Model: Tesla

Key Features of Constructors in Java

There are several important features of constructors in Java that you should keep in mind. They are as:

1. Same Name as Class: A constructor must have the same name as the class in which it is defined. For example:

class Car {
    Car() {  // Constructor with the same name as the class
        System.out.println("Car object created");
    }
}

2. No Return Type: A constructor does not have a return type, not even void as well. If you specify a return type, Java will treat as a normal method rather than a constructor.

3. Automatically Called: When you create an object of a class using the new keyword, Java automatically calls the constructor of that class. You do not need to call the constructor explicitly unlike regular methods. For example:

public class Dog {
 // Constructor definition.
    Dog() {
        System.out.println("Dog constructor called!");
    }
public static void main(String[] args) {
 // Create an object of class Dog.
    Dog myDog = new Dog(); // Dog constructor is called automatically. 
  }
}
Output:
    Dog constructor called! 

4. Supports Overloading: Java allows you to define multiple constructors with different parameter lists in the same class. For example:

class Student {
    String name;
    int age;

 // Default constructor definition.
    Student() {
        this.name = "Unknown";
        this.age = 0;
    }
 // Parameterized constructor definition.
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

In this example, both constructors are overloaded. You will understand about it in more detail in the constructor overloading chapter.

5. Constructor Chaining: A constructor can call another constructor within the same class using this() keyword. For example:

class Employee {
    String name;
    int age;

    Employee() {
        this("Default", 0); // Calling another constructor in the same class.
    }

    Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

6. Cannot Be Inherited: Constructors are not inherited by subclasses, but they can be called using super(). For example:

class Parent {
    Parent() {
        System.out.println("Parent Constructor");
    }
}
class Child extends Parent {
    Child() {
        super(); // This statement calls the parent class constructor.
        System.out.println("Child Constructor");
    }
}

7. Can Be Private: A constructor can be private using private access modifier to restrict object creation from outside the class. It is mainly useful in singleton design pattern. For example:

class Singleton {
    private static Singleton instance;
    private Singleton() {} // Declaration of Private constructor

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

When Exactly is the Constructor Called?

The constructor is called immediately after memory allocation, right when new is executed in the program. Look at the below step-by-step process:

  • new keyword triggers memory allocation in heap area.
  • Default values are assigned by the default constructor. For example, the default values of int and string are zero, null, respectively.
  • Constructor executes and initializes fields, or runs logic.
  • Object reference is returned.

Example: Behind the Scenes

MyClass obj = new MyClass();

JVM Actions:

  • Allocates memory for MyClass.
  • Sets default values (null, 0, false, etc.).
  • Calls MyClass() constructor.
  • Returns the reference to obj.

What If There is No Constructor?

If you do not define any constructor in the Java program, Java compiler automatically adds a default constructor. For example:

class Test { 
   // No constructor.
}  

Java Compiler adds:

class Test { 
// Default constructor added with empty body.
   Test() { 

   }  
} 

But if you define any constructor, Java won’t provide the default one. For example:

class Test { 
    Test(int x) { 

    } 
}  
// No default constructor
Test t = new Test(); // ERROR! No zero-arg constructor exists.

Types of Constructors in Java

There are several types of constructors in Java that are as follows:

  • Default constructor
  • Parameterized constructor
  • Copy constructor
  • Constructor overloading
  • Constructor chaining
  • Private constructor

Let’s explore each type with examples.

Default Constructor

A constructor that does not take any parameters and initializes objects with default values is called default constructor in Java. If you do not define any constructor explicitly in the program, Java compiler provides a default constructor with no parameters and empty body.

Default Values of Different Data Types in Java

Data TypeDefault Value
byte0
short0
int0
long0L
float0.0f
double0.0d
char\u0000 (null character)
booleanfalse
String (or any object)null

Example 2: Checking Default Values

class DefaultValues {
    int num;         // Default: 0
    double decimal;  // Default: 0.0
    boolean flag;    // Default: false
    String text;     // Default: null

// No constructor defined → Java provides default constructor here.

// Declare a method named displayValues.
   void displayValues() {
        System.out.println("int: " + num);
        System.out.println("double: " + decimal);
        System.out.println("boolean: " + flag);
        System.out.println("String: " + text);
   }
// Main method.
   public static void main(String[] args) {
   // Creating an object of class.
      DefaultValues obj = new DefaultValues(); // Default constructor called.
      obj.displayValues(); // Calling method.
   }
}
Output:
     int: 0
     double: 0.0
     boolean: false
     String: null

Note: Default values apply only to instance variables declared inside a class. Local variables must be initialized before use, otherwise, the compiler will throw an error.

Example 3: Default Constructor with Body

class Car {
 // Default constructor definition.
    Car() {
        System.out.println("A car object is created.");
    }
    public static void main(String[] args) {
        Car myCar = new Car(); // Constructor is called automatically.
    }
}
Output:
      A car object is created.

Parameterized Constructor

A constructor that accepts parameters (or arguments) to initialize object properties with specific values is called parameterized constructor in Java programming. This type of constructor allows you to pass arguments to the constructor during the object creation. Parameterized constructor allows dynamic initialization of objects. The general syntax of parameterized constructor in Java is as follows:

public class ClassName {
 // Fields (instance variables)
    dataType field1;
    dataType field2;

 // Parameterized Constructor
    ClassName(dataType param1, dataType param2, ...) {
     // Assign parameters to fields
        this.field1 = param1;
        this.field2 = param2;
     // Additional initialization (if needed)
    }
}

In the above syntax of parameterized constructor, we have used this keyword to distinguish between instance variables and parameters.

Example 4: Basic Parameterized Constructor

public class Employee {
    String name;
    int id;

 // Parameterized constructor definition.
    Employee(String empName, int empId) {
        name = empName;
        id = empId;
    }
// Main method
   public static void main(String[] args) {
 // Create an object of class Employee and pass arguments to its parameterized constructor. 
      Employee emp = new Employee("John", 101);
      System.out.println("Name: " + emp.name + ", ID: " + emp.id);
   }
}
Output:
     Name: John, ID: 101

Example 5:

public class Student {
    String name;
    int rollNo;

 // Creating parameterized constructor.
    Student(String name, int rollNo) {
        this.name = name;
        this.rollNo = rollNo;
    }
  public static void main(String[] args) {
   // Creating object with dynamic values
      Student s1 = new Student("Saanvi", 10);
      System.out.println("Name: " + s1.name + ", Roll No: " + s1.rollNo);
    }
}
Output:
      Name: Saanvi, Roll No: 10

In this example, the constructor Student(String name, int rollNo) takes two arguments. The line this.name refers to the instance variable, while name refers to the parameter.

Constructor Overloading in Java

When you define multiple constructors in the same class but with different parameters, then it is called constructor overloading in Java. This concept allows you to define multiple constructors with different parameters. Let’s take a simple example on this concept.

Example 6: Basic Constructor Overloading

public class Rectangle {
    int length, width;

 // Constructor definition 1: No-args (default)
    Rectangle() {
        length = 0;
        width = 0;
    }

 // Constructor definition 2: One parameter (square)
    Rectangle(int side) {
        length = width = side;
    }

 // Constructor definition 3: Two parameters (rectangle)
    Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }

    public static void main(String[] args) {
        Rectangle r1 = new Rectangle();       // Default (0, 0)
        Rectangle r2 = new Rectangle(5);      // Square (5, 5)
        Rectangle r3 = new Rectangle(4, 6);  // Rectangle (4, 6)

        System.out.println("r1: " + r1.length + "x" + r1.width); 
        System.out.println("r2: " + r2.length + "x" + r2.width);
        System.out.println("r3: " + r3.length + "x" + r3.width); 
    }
}
Output:
     r1: 0x0  
     r2: 5x5  
     r3: 4x6  

Example 7:

class Box {
    double width, height, depth;

 // Default Constructor
    Box() {
        width = height = depth = 0;
    }
 // Parameterized Constructor
    Box(double w, double h, double d) {
        width = w;
        height = h;
        depth = d;
    }
    void displayVolume() {
        System.out.println("Volume: " + (width * height * depth));
    }
 public static void main(String[] args) {
     Box b1 = new Box(); // Default constructor called.
     Box b2 = new Box(2, 3, 4); // Parameterized constructor called.
     b2.displayVolume(); // Method calling.
  }
}
Output:
      Volume: 24.0

Constructor Chaining in Java

When a constructor can call another constructor in the same class using this(), then this concept is called constructor chaining in Java. The general syntax of constructor chaining is as follows:

class ClassName {
 // Constructor 1
    ClassName() {
        this(value1, value2); // Calls another constructor
    }

 // Constructor 2
    ClassName(datatype param1, datatype param2) {
        // Initialization
    }
}

Example 8: Basic Constructor Chaining

class Employee {
    String name;
    int age;

 // Default Constructor
    Employee() {
        this("Unknown", 0); // This line will call the parameterized constructor.
    }
 // Parameterized Constructor
    Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
    void display() {
        System.out.println("Employee Name: " + name + ", Age: " + age);
    }
    public static void main(String[] args) {
        Employee e1 = new Employee();
        Employee e2 = new Employee("David", 30);
        e1.display();
        e2.display();
    }
}
Output:
     Employee Name: Unknown, Age: 0
     Employee Name: David, Age: 30

Example 9:

public class Person {
    String name;
    int age;
    String city;

 // Constructor 1: Default
    Person() {
        this("Unknown", 0); // Calls Constructor 2
    }

 // Constructor 2: Two parameters
    Person(String name, int age) {
        this(name, age, "Unknown"); // Calls Constructor 3
    }

 // Constructor 3: Three parameterized
    Person(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }

public static void main(String[] args) {
    Person p1 = new Person();                    
    Person p2 = new Person("Alice", 25);          
    Person p3 = new Person("Bob", 30, "New York");

    System.out.println(p1.name + ", " + p1.age + ", " + p1.city);
    System.out.println(p2.name + ", " + p2.age + ", " + p2.city);
    System.out.println(p3.name + ", " + p3.age + ", " + p3.city);
  }
}
Output:
      Unknown, 0, Unknown  
      Alice, 25, Unknown  
      Bob, 30, New York  

Copy Constructor in Java

A constructor that creates a new object by copying values from another existing object is called copy constructor in Java. Let’s take an example on this concept.

Example 10:

class Student {
    String name;
    int id;

 // Creating a parameterized constructor.
    Student(String name, int id) {
        this.name = name;
        this.id = id;
    }

 // Creating a copy constructor.
    Student(Student s) {
        this.name = s.name;
        this.id = s.id;
    }
    void display() {
        System.out.println("Student Name: " + name + ", ID: " + id);
    }
    public static void main(String[] args) {
        Student s1 = new Student("Saanvika", 10);
        Student s2 = new Student(s1); // Copying values
        s2.display();
    }
}
Output:
      Student Name: Saanvika, ID: 10

Private Constructor

When you apply private access modifier with a constructor, then it is called private constructor in Java. This type of constructor allows you to prevent object creation from outside the class. It is mainly used in design patterns (like Singleton Pattern) and utility classes where external instantiation should be restricted.

Private constructor can be accessed only within the same class. The general syntax to define a private constructor in a class is as follows:

public class MyClass {
 // Creating a constructor with private access modifier.
    private MyClass() {
        // Initialization code (if needed)
    }

 // Other methods (usually static)
    public static void doSomething() {
        System.out.println("Static method called!");
    }
}

❌ What Happens If You Try to Instantiate?

MyClass obj = new MyClass(); // COMPILE-TIME ERROR!

Example 11: Singleton with Private Constructor

public class Database {
    private static Database instance;

 // Private Constructor.
    private Database() {
        System.out.println("Database connected!");
    }

 // Global access point
    public static Database getInstance() {
        if (instance == null) {
            instance = new Database(); // Only one instance is created.
        }
        return instance;
    }
}
public class Main {
public static void main(String[] args) {
      Database db1 = Database.getInstance();
      Database db2 = Database.getInstance();
      System.out.println(db1 == db2);
  }
}
Output:
      Database connected!  
      true  

Example 12: Custom Utility Class

public class Logger {
  private String logLevel; // private instance variable.

 // Creating a private constructor.
    private Logger(String level) {
        this.logLevel = level;
    }

 // Factory Method.
    public static Logger createLogger(String level) {
        if (level.equals("DEBUG") || level.equals("ERROR")) {
            return new Logger(level);
        }
        throw new IllegalArgumentException("Invalid log level!");
    }
}
public class Main {
public static void main(String[] args) {
   Logger debugLogger = Logger.createLogger("DEBUG"); // Allowed.
// Logger invalidLogger = new Logger("DEBUG"); // Error because of private constructor.
    }
}

Difference Between Constructor and Method

FeatureConstructorMethod
NameSame as class name.Any valid and logical name.
Return TypeNoneRequired (voidint, etc.)
InvocationCalled automatically with new keyword.Called explicitly.
PurposeInitialize objectsPerform operations

Conclusion

In this tutorial, you learned about constructor in Java with the help of important examples. The syntax of a Java constructor follows strict rules such as having the same name as the class and no return type. You must keep in mind this rule to define a constructor in a program. I hope that you will have understand the basic concepts of constructor overloading, constructor chaining, and copy constructor.

Please Share Your Love.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *