What is Constructor in Java? (Complete Guide with Examples)

what is constructor in java

When learning Java, one of the first things you will come across is the concept of a constructor. Constructors are also important in the object-oriented programming since they initialize objects. Having a good grasp of constructors will bolster your Java basics and enable you to produce a cleaner and more efficient code.

This step-by-step tutorial will teach you all about constructors in Java, starting with simple definitions, up through the sophisticated use and specifics, types, examples, and good practices.

What is a Constructor in Java?

A Java method, which is automatically invoked upon the creation of an object of a class, is known as a constructor. It is primarily used to set up the properties of the object (variables).

Unlike regular methods, a constructor:

  • Has the same name as the class
  • Does not have a return type (not even void)
  • Is called automatically when an object is created with the new keyword.

Simple Definition:

A constructor is a special method used to initialize objects in Java.

Why Do We Need Constructors?

In creating an object, you find that you want to give values to it at once. Constructors simplify this process and make it organized.

Without Constructor:

After creating the object, you would have to provide the values manually.

With Constructor:

All of this can be initialized when creating an object.

Example of Constructor in Java

class Student {

   String name;

   int age;

   // Constructor

   Student() {

       name = “Unknown”;

       age = 0;

   }

   void display() {

       System.out.println(name + ” ” + age);

   }

}

public class Main {

   public static void main(String[] args) {

       Student s1 = new Student(); // Constructor is called

       s1.display();

   }

}

Output:

Unknown 0

Types of Constructors in Java

Java mainly supports three types of constructors:

1. Default Constructor

2. Parameterized Constructor

3. Copy Constructor (User-defined)

Constructor Types Table

Constructor TypeDescriptionExample Use Case
Default ConstructorNo parameters, assigns default valuesInitialize object with default settings
Parameterized ConstructorAccepts parameters to initialize variablesSet values during object creation
Copy ConstructorCopies values from another objectClone or duplicate objects

1. Default Constructor

A default constructor does not take any parameters. If you don’t create any constructor, Java automatically provides one.

Example:

class Car {

   String brand;

   Car() {

       brand = “Toyota”;

   }

   void show() {

       System.out.println(brand);

   }

}

2. Parameterized Constructor

A parameterized constructor allows you to pass values while creating the object.

Example:

class Car {

   String brand;

   Car(String b) {

       brand = b;

   }

   void show() {

       System.out.println(brand);

   }

}

public class Main {

   public static void main(String[] args) {

       Car c1 = new Car(“BMW”);

       c1.show();

   }

}

Output:

BMW

3. Copy Constructor

Java does not provide a built-in copy constructor like some other languages, but you can create one manually.

Example:

class Student {

   String name;

   int age;

   // Copy constructor

   Student(Student s) {

       name = s.name;

       age = s.age;

   }

   Student(String n, int a) {

       name = n;

       age = a;

   }

   void display() {

       System.out.println(name + ” ” + age);

   }

}

Constructor Overloading in Java

Java allows multiple constructors in the same class, as long as they have different parameters. This is called constructor overloading.

Example:

class Demo {

   Demo() {

       System.out.println(“Default Constructor”);

   }

   Demo(int x) {

       System.out.println(“Parameterized Constructor: ” + x);

   }

}

Important Rules of Constructors

what is constructor in java

Here are some important rules you must remember:

  • Constructor name must match the class name
  • It does not have a return type
  • It is called automatically when object is created
  • It can be overloaded
  • It cannot be inherited
  • It can use access modifiers (public, private, protected)

Difference Between Constructor and Method

FeatureConstructorMethod
NameSame as classAny name
Return TypeNo return typeMust have return type
InvocationCalled automaticallyCalled manually
PurposeInitialize objectPerform operations

The Keyword in Constructor

The keyword is used to refer to the current object.

Example:

class Student {

   String name;

   Student(String name) {

       this.name = name; // differentiate variable

   }

}

Constructor Chaining

Constructor chaining means calling one constructor from another using this().

Example:

class Demo {

   Demo() {

       this(10);

       System.out.println(“Default Constructor”);

   }

   Demo(int x) {

       System.out.println(“Parameterized: ” + x);

   }

}

Private Constructors

A constructor can be declared private to restrict object creation.

Example:

class Singleton {

   private Singleton() {

       System.out.println(“Private Constructor”);

   }

}

This is commonly used in Singleton Design Pattern.

Real-Life Example of Constructor

Think of a constructor like a form you fill when creating an account.

  • Class = Account template
  • Constructor = Form filling process
  • Object = Your created account

When you create an account, details are initialized immediately — just like a constructor.

Advantages of Constructors

  • Automatically initializes objects
  • Makes code clean and readable
  • Reduces extra lines of code
  • Supports overloading for flexibility
  • Helps enforce object consistency

Common Mistakes to Avoid

  • Giving return type to constructor
  • Using wrong class name
  • Forgetting to initialize variables
  • Confusing constructor with method

When Should You Use Constructors?

You should use constructors when:

  • You want to initialize object variables immediately
  • You need mandatory values during object creation
  • You want to reduce repetitive code

Conclusion

The constructors are an essential aspect of Java and object-oriented design. They enable you to initialize objects in an efficient manner and make sure that all objects are initially in a valid state.

Regardless of whether you are initializing with a default constructor, to get simple initializing, or with a parameterized constructor, to get flexibility, understanding constructors will greatly enhance your Java coding abilities.

Constructors are not a luxury, but a necessity, if you want to do any serious Java development.

Leave a Reply

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