Advanced
Data Structures Algorithms & System Design(HLD+LLD)
by Logicmojo

Cracking FAANG companies interviews with a few months of preparation

Learn Advanced Data Structures, Algorithms & System Design

Online live classes from 4 to 7 months programs

Get job assistance after course completion

Download Course Brochure

Constructor in OOPs

Back to home
Logicmojo - Updated Dec 12, 2022



What is Constructor?

A constructor is a special method of a class or structure in object-oriented programming that initializes a newly created object of that type. Whenever an object is created, the constructor is called automatically.





A constructor resembles an instance method, but it differs from a method in that it has no explicit return type, it is not implicitly inherited and it usually has different rules for scope modifiers. Constructors often have the same name as the declaring class. They have the task of initializing the object's data members and of establishing the invariant of the class, failing if the invariant is invalid. A properly written constructor leaves the resulting object in a valid state. Immutable objects must be initialized in a constructor.

Most languages allow overloading the constructor in that there can be more than one constructor for a class, with differing parameters. Some languages take consideration of some special types of constructors. Constructors, which concretely use a single class to create objects and return a new instance of the class, are abstracted by factories, which also create objects but can do so in various ways, using multiple classes or different allocation schemes such as an object pool.

Constructor enables an object to initialize itself at the time of its creation without the need to make a separate call to the instance method. It looks like a method but it is different from the method in two ways as follow

  1. A constructor always has the same name as the class whose instance members they initialize.

  2. It also does not have a return type and not even void like methods. It causes the compiler to automatically call the constructor whenever an object of the class is created.

Rules for creating Constructor

  1. 1. Name of the constructor and name of the class must be same.

  2. 2. Return type concept is not applicable for constructor even void also by mistake if we are declaring the return type for the constructor we won’t get any compile time error and runtime error compiler simply treats it as a method.

  3. 3. It is legal (but stupid) to have a method whose name is exactly same as class name.

  4. 4. The only applicable modifiers in java for the constructors are public, default, private, protected.

  5. 5. If we are using any other modifier we will get compile time error.

Types of Constructor

There are two types of constructors in Java:

  1. 1. Default constructor (no-arg constructor)

  2. 2. Parameterized constructor

Default Constructor

Whenever we create an object, a constructor is invoked. In case we did not create any constructor, the compiler will automatically write one for us. This constructor known as default constructor. It does not have any parameters and any statement in its body. The main aim of default constructor is to enable you to create an object of a class type. When the compiler create a default constructor, It does nothing. The objects created the default constructor will have fields with their default values.

Example

<
class Display {

  int a;
  boolean b;

  public static void main(String[] args) {

    // A default constructor is called
    Display obj = new Display();

    System.out.println("Default Value:");
    System.out.println("a = " + obj.a);
    System.out.println("b = " + obj.b);
  }
}

Parameterized Constructor

Unlike default constructor, parameterized constructor have one or more parameters. This type of constructor, it is possible to initialize objects with different set of values at the time of creation. These different set of value initialized to objects must pass as an arguments when the constructor is invoked. The list of parameter can be specified in the parentheses in the same way as parameters are specified in the methods.

Example

class Display {

  String languages;

  // constructor accepting single value
  Display(String lang) {
    languages = lang;
    System.out.println(languages + " Programming Language");
  }

  public static void main(String[] args) {

    // call constructor by passing a single value
   Display obj1 = new Display("Java");
    Display obj2 = new Display("Python");
    Display obj3 = new Display("C");
  }
}


Overloaded Constructor

A class can contain more than one constructor and all these constructors having the same name but different arguments and hence these constructors are considered as overloaded constructors.

Example

class Test
{
	Test(double d)
	{
		this(10);
		System.out.println("double-argument constructor");
	}
	Test(int i)
	{
		this();
		System.out.println("int-argument constructor");
	}
	Test()
	{
		System.out.println("no-argument constructor");
	}
	public static void main(String[] args)
	{
		Test t1=new Test(10.5);//no-argument constructor/int-argument constructor/double-argument constructor
		Test t2=new Test(10);//no-argument constructor/int-argument constructor
		Test t3=new Test();//no-argument constructor
	}
}

Inheritance concept is not applicable for constructors and hence overriding concept also not applicable to the constructors. But constructors can be overloaded”.

Advantages of Constructor

  1. A constructor eliminates placing the default values.

  2. A constructor eliminates calling the normal method implicitly.

With this article at Logicmojo, you must have the complete idea of Constructor in OOPs






Frequently Asked Questions (FAQs)


In object-oriented programming, a constructor is a special method within a class that is used to initialize and create objects of that class. It is called automatically when an instance of the class is created. Constructors have the same name as the class they belong to and can have parameters to accept values that are necessary for object initialization.

The purpose of a constructor is to ensure that the object being created starts with valid and appropriate initial values for its attributes or properties. It allows you to set the initial state of an object, allocate necessary resources, and perform any necessary setup tasks.

Here's an example to illustrate the concept of constructors in Java:

public class Car {
    private String make;
    private String model;
    private int year;

    // Constructor with parameters
    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    // Getters and setters
    // ...

    public static void main(String[] args) {
        // Creating instances of the Car class using the constructor
        Car car1 = new Car("Toyota", "Camry", 2021);
        Car car2 = new Car("Honda", "Accord", 2022);

        // Accessing the attributes of car1 and car2
        System.out.println("Car 1: " + car1.getMake() + " " + car1.getModel() + " " + car1.getYear());
        System.out.println("Car 2: " + car2.getMake() + " " + car2.getModel() + " " + car2.getYear());
    }
}

In this example, we have a `Car` class with attributes `make`, `model`, and `year`. The class has a constructor that takes three parameters: `make`, `model`, and `year`. When an instance of the `Car` class is created using the `new` keyword, the constructor is automatically called, and the provided values are used to initialize the object.

In the `main` method, we create two instances of the `Car` class, `car1` and `car2`, by calling the constructor with different arguments. The constructor assigns the provided values to the respective attributes of the objects.

Finally, we access the attributes of `car1` and `car2` using getter methods (not shown in the example) to retrieve and display the information.

Constructors are essential for creating objects and ensuring proper initialization. They allow us to control the initial state of objects and provide flexibility in setting the initial values of attributes based on the provided arguments.



In object-oriented programming (OOP), a constructor is a special method within a class that is used to initialize objects of that class. It is automatically called when an instance (object) of the class is created. The purpose of a constructor is to ensure that the object being created starts with valid and appropriate initial values for its attributes or properties.

Constructors have the same name as the class they belong to, and they may take parameters to accept values that are necessary for object initialization. By defining constructors, you define the rules for creating objects of the class, ensuring that objects are properly set up and ready to be used.

Here are some key points about constructor methods:

1. Initialization: Constructors are responsible for initializing the state of objects. They allocate memory for the object and set the initial values of its attributes. By defining a constructor, you ensure that objects start with a valid and consistent state.

2. Automatic Invocation: Constructors are automatically called when an object is created using the `new` keyword. When an instance of a class is created, the constructor is executed to perform the necessary initialization tasks.

3. Same Name as Class: Constructors have the same name as the class they belong to. This allows the programming language to identify and associate the constructor with the class. By convention, constructor names start with an uppercase letter to differentiate them from other methods.

4. Overloading: Constructors can be overloaded, meaning that a class can have multiple constructors with different parameter lists. Overloading allows you to create objects using different sets of arguments, providing flexibility in object creation.

5. No Return Type: Constructors do not have an explicit return type. They do not return values explicitly because their purpose is to create and initialize objects rather than compute and return values.

6. Initialization Order: If a class has multiple constructors, they can be chained together to handle different scenarios or overloadings. This allows you to reuse common initialization logic across different constructors.

7. Default Constructor: If no constructors are explicitly defined in a class, a default constructor is automatically provided by the programming language. The default constructor initializes the object with default values or initializes primitive types to their default values (e.g., 0 for integers, false for booleans).

Constructors play a vital role in object-oriented programming as they ensure that objects are properly initialized before they are used. They encapsulate the logic for object creation and set the foundation for objects to interact with one another and perform their intended tasks. By defining constructors, you establish the rules and requirements for creating instances of a class, enforcing the necessary initialization and setup procedures.


In object-oriented programming, constructors can be classified into three types based on their characteristics and usage:

1. Default Constructor:

- A default constructor is automatically provided by the programming language if no constructors are explicitly defined in a class.

- It is parameterless, meaning it takes no arguments.

- The default constructor initializes the object with default values or initializes primitive types to their default values (e.g., 0 for integers, false for booleans).

- It allows for the creation of objects without passing any initial values.

- The default constructor is useful when the object does not require any specific initialization logic or when the attributes have default values that are sufficient.

2. Parameterized Constructor:

- A parameterized constructor is a constructor that accepts parameters to initialize the object with specific values.

- It allows for the creation of objects with customized initial values.

- The parameterized constructor takes arguments corresponding to the attributes of the class and assigns the provided values to the attributes during object creation.

- By defining multiple parameterized constructors with different parameter lists (overloading), you can provide flexibility in object creation by allowing different sets of arguments.

- Parameterized constructors are useful when objects need specific values for proper initialization or when customization of initial values is required.

3. Copy Constructor:

- A copy constructor is used to create a new object by copying the values of an existing object of the same class.

- It takes an object of the same class as a parameter and creates a new object with the same attribute values.

- The copy constructor is useful when you want to create a new object that is an exact copy of an existing object, including all attribute values.

- It ensures that the new object is a separate instance with its own memory, rather than just creating a reference to the existing object.

- The copy constructor is commonly used when dealing with object cloning, deep copying, or creating independent copies of objects.

By having these three types of constructors, you can control the object creation process and ensure that objects are properly initialized. The default constructor provides a fallback initialization mechanism, the parameterized constructor allows for customization of initial values, and the copy constructor facilitates object cloning and copying. The choice of constructor type depends on the specific requirements and needs of the application and the class being implemented.


The term "constructor" in programming originates from the idea that the purpose of this special method is to construct or create an object. The word "constructor" is derived from the verb "construct," which means to build or assemble something. In the context of object-oriented programming, a constructor is responsible for constructing an object by initializing its attributes or properties and setting it up for use.

Here are a few reasons why the term "constructor" is used to describe this special method:

1. Object Creation: Constructors are called when an object is created or "constructed" using the `new` keyword. They are responsible for allocating memory for the object and setting its initial state, just as a constructor in the real world builds or assembles a physical object from its constituent parts.

2. Initialization: Constructors initialize the attributes or properties of an object, ensuring that it starts with valid and appropriate initial values. They construct the object by assigning values to its attributes, just as a constructor in the real world constructs an object by providing the necessary parts or elements.

3. Object Setup: Constructors perform any necessary setup tasks required for the object to be ready for use. They may perform operations such as opening connections, allocating resources, or initializing dependencies. This process of setting up the object is analogous to the construction of a physical object, where various components are assembled and prepared for use.

4. Class Blueprint: Constructors are defined within a class, which serves as a blueprint or template for creating objects. The class provides the structure and behavior that define the type of objects to be created. Constructors define how the object should be constructed based on the class blueprint.

By using the term "constructor," programming languages communicate the concept that this special method is responsible for constructing an object by initializing it, setting it up, and preparing it for use. It emphasizes the idea that creating an object involves more than just allocating memory; it involves the necessary initialization and setup steps to ensure the object's proper state and behavior. The term "constructor" serves as a fitting descriptor for this essential process in object-oriented programming.


In object-oriented programming (OOP) using C++, a constructor is a special member function of a class that is automatically called when an object of that class is created. The purpose of a constructor is to initialize the object and set its initial state.

In C++, the constructor has the same name as the class and does not have a return type, not even void. Constructors are used to allocate memory for objects, initialize the member variables, and perform any necessary setup tasks. They ensure that the object being created starts with valid and appropriate initial values.

Here are some key points about constructors in C++:

1. Default Constructor:

- If a class does not have any explicitly defined constructors, the compiler provides a default constructor.

- The default constructor is parameterless, and it initializes the member variables of the class with their default values (e.g., 0 for integers, false for booleans).

- The default constructor can be explicitly defined by the programmer if custom initialization logic is required.

2. Parameterized Constructor:

- A parameterized constructor is a constructor that accepts parameters to initialize the object with specific values.

- It allows for customization of the initial values of the member variables.

- The parameterized constructor can be overloaded, meaning multiple constructors can be defined with different parameter lists, enabling flexibility in object creation.

3. Copy Constructor:

- The copy constructor is a special type of constructor used to create a new object as a copy of an existing object.

- It takes a reference to an object of the same class as a parameter and creates a new object with the same attribute values.

- The copy constructor is used when objects need to be copied or cloned, ensuring that the new object is an independent copy with its own memory.

4. Initialization List:

- Constructors in C++ can use an initialization list to initialize member variables directly.

- The initialization list appears after the constructor's parameters and before the opening brace of the constructor's body.

- Initialization lists are useful for initializing member variables that cannot be assigned values after the object is created or for efficiently initializing variables that require complex initialization logic.

5. Multiple Constructors:

- A class can have multiple constructors with different parameter lists, allowing for various ways to create objects of that class.

- This feature is called constructor overloading, where different constructors can be defined with different sets of parameters to handle different scenarios or provide different initialization options.

Constructors play a crucial role in C++ OOP as they ensure that objects are properly initialized and set up before they are used. They allow for customization of initial values, handle object cloning and copying, and define the behavior for object creation. By defining constructors, you control how objects of your class are created and ensure that they start with a valid and consistent state.


To create a constructor in C++, you define a special member function within your class. Here's a step-by-step guide on how to create a constructor:

1. Define the Constructor:

- Constructors have the same name as the class they belong to.

- Constructors do not have a return type, not even void.

- Constructors are declared in the public section of the class, allowing them to be accessible for object creation.

2. Specify the Parameters (if needed):

- Constructors can be parameterized to accept values necessary for object initialization.

- Specify the parameters within the parentheses following the constructor's name.

- The number and type of parameters are based on your specific requirements.

3. Implement the Constructor:

- The constructor's implementation is defined outside the class declaration.

- It initializes the member variables of the class and performs any necessary setup tasks.

- Use the constructor's body (enclosed within curly braces {}) to specify the initialization logic.

4. Use the Constructor:

- When an object of the class is created using the `new` keyword or by declaring it as a local variable, the constructor is automatically called.

- Arguments can be passed to the constructor if it is parameterized, providing the necessary values for object initialization.

Here's an example demonstrating the creation and usage of a constructor in C++:

class Rectangle {
private:
    int length;
    int width;

public:
    // Constructor with parameters
    Rectangle(int len, int wid) {
        length = len;
        width = wid;
    }

    // Member function to calculate the area
    int calculateArea() {
        return length * width;
    }
};

int main() {
    // Create an object using the constructor with parameters
    Rectangle rect(5, 3);

    // Call the member function to calculate the area
    int area = rect.calculateArea();
    std::cout << "Area: " << area << std::endl;

    return 0;
}

In this example, the `Rectangle` class has a constructor that takes two parameters, `len` and `wid`, to initialize the `length` and `width` member variables. Inside the constructor, the values passed as arguments are assigned to the respective member variables.

In the `main` function, an object of the `Rectangle` class is created using the constructor with parameters: `Rectangle rect(5, 3)`. This automatically calls the constructor and initializes the `length` and `width` of the `rect` object with the provided values.

Finally, the `calculateArea` member function is called on the `rect` object to calculate the area, and the result is printed to the console.

By defining and using constructors, you can control the initialization of objects and ensure they start with valid initial values. Constructors allow you to customize the creation process and set up objects for their intended use.


Constructors are used in object-oriented programming to ensure that objects are properly initialized and set up before they are used. They serve several important purposes:

1. Object Initialization: Constructors initialize the member variables or attributes of an object. They ensure that the object starts with valid and appropriate initial values. By setting initial values, constructors establish the object's initial state, allowing it to be in a consistent and usable state from the moment it is created.

2. Memory Allocation: Constructors are responsible for allocating memory for objects. When an object is created, constructors handle the allocation of memory needed to store the object's data. This ensures that the necessary memory is properly reserved and available for the object's use.

3. Encapsulation: Constructors are part of the encapsulation principle in object-oriented programming. They provide a way to encapsulate the object creation process within the class itself. By defining constructors as part of the class, the object's creation and initialization logic are kept within the class's scope, promoting encapsulation and information hiding.

4. Custom Initialization: Constructors allow for custom initialization of objects. By defining constructors with parameters, you can provide flexibility in object creation and allow clients of your class to specify initial values or configurations. Constructors with parameters enable objects to be created with specific initial states based on the provided arguments.

5. Object Setup: Constructors perform any necessary setup tasks required for the object to be ready for use. They may involve initializing resources, establishing connections, or configuring dependencies. Constructors allow you to perform initialization logic that is essential for the object's functionality and usability.

6. Object Cloning: Copy constructors, a type of constructor, enable the creation of new objects as copies of existing objects. They provide a way to clone or duplicate objects, ensuring that the new object is an independent copy with its own memory. Copy constructors are useful when you need to create a copy of an object without sharing the same memory space.

7. Object Lifetime: Constructors determine the lifetime of objects. When an object is created, its constructor is automatically called, ensuring that the object is properly initialized and ready for use. Similarly, when an object goes out of scope or is explicitly destroyed, its destructor (a special member function) is called to release any allocated resources and perform cleanup tasks.

By using constructors, you establish the rules and requirements for creating instances of a class. They help enforce the necessary initialization and setup procedures, promoting the creation of well-formed and usable objects. Constructors contribute to the reliability, integrity, and proper functioning of objects in an object-oriented system.


Constructor overloading is a feature in object-oriented programming that allows a class to have multiple constructors with different parameter lists. Each constructor can accept a different set of arguments, providing flexibility in object creation and initialization.

In constructor overloading, you define multiple constructors within a class, each with a unique parameter list. The choice of which constructor to invoke is determined by the arguments passed during object creation. The appropriate constructor is selected based on the number, types, and order of the arguments provided.

Here are some key points about constructor overloading:

1. Multiple Constructors: With constructor overloading, a class can have more than one constructor, each with a different signature. The signature of a constructor includes the number, types, and order of its parameters.

2. Different Parameter Lists: Each overloaded constructor has a unique parameter list. The parameters can have different types, different numbers of parameters, or a different order of parameters. This allows constructors to accept different combinations of values during object creation.

3. Flexibility in Object Creation: Constructor overloading provides flexibility in creating objects. It allows clients of the class to choose the most appropriate constructor based on their requirements and the data they have available. Clients can select the constructor that matches the specific initialization needs of the object they want to create.

4. Initialization Variations: Overloaded constructors can provide different variations of object initialization. Each constructor can perform a specific initialization logic based on the provided arguments. This enables objects to be created and initialized in different ways, depending on the available data or the desired initial state.

5. Constructor Chaining: Overloaded constructors can be chained together, meaning one constructor can call another constructor within the same class. This allows shared initialization logic to be centralized in one constructor and reused by other constructors. Constructor chaining simplifies code duplication and promotes code maintainability.

6. Default Constructor: Overloaded constructors can include a default constructor (parameterless constructor) to handle scenarios where no specific initialization is required or when the client does not provide any arguments during object creation.


In object-oriented programming, a constructor cannot be abstract. An abstract method is a method that is declared in an abstract class or interface but does not have an implementation. It is meant to be overridden by the subclasses that inherit from the abstract class or implement the interface.

Constructors, on the other hand, are special member functions that are responsible for initializing objects of a class. They cannot be abstract because they require a specific implementation to allocate memory and set up the initial state of an object. Every class must have a constructor, even if it is the default constructor provided by the compiler.

Here are some reasons why constructors cannot be abstract:

1. Object Initialization: Constructors play a crucial role in initializing objects by allocating memory and setting initial values. They ensure that objects start in a valid and usable state. An abstract constructor would not have a specific implementation to perform this important initialization process, rendering the object in an incomplete state.

2. Incomplete Objects: An abstract constructor would result in incomplete objects that cannot be created or used directly. Since abstract methods do not have implementations, the object creation process would lack the necessary steps to properly initialize the object's state. As a result, the object would be unable to fulfill its intended purpose or behave correctly.

3. Inheritance and Subclassing: Abstract classes and interfaces are used as blueprints for creating subclasses or implementing interfaces. They provide a common structure and behavior that can be extended or implemented by subclasses. Constructors are inherited by subclasses, allowing them to initialize the inherited attributes and perform any additional setup tasks. If constructors were abstract, the subclass would be unable to inherit or invoke the necessary constructor to create and initialize objects.

4. Direct Object Creation: Constructors are invoked directly during object creation using the `new` keyword or by declaring objects as local variables. Abstract methods cannot be invoked directly because they lack implementation. Similarly, abstract constructors would not be able to perform the necessary object creation and initialization tasks.

In summary, constructors cannot be abstract because they are responsible for initializing objects and ensuring that they start in a valid state. Constructors require specific implementation details to allocate memory, set initial values, and perform any necessary setup tasks. Abstract methods, on the other hand, lack implementation and are meant to be overridden by subclasses or implemented by implementing classes.


Yes, a constructor can be declared as private in a class. When a constructor is declared as private, it means that it can only be accessed and invoked within the class itself. It restricts the creation of objects from outside the class, effectively preventing direct instantiation of objects by external code.

Here are some points to understand about private constructors:

1. Access Restriction: Making a constructor private restricts its access to only the members and functions within the class. It hides the constructor from the outside world, preventing external code from directly creating objects using that constructor.

2. Singleton Pattern: One common use of a private constructor is in the implementation of the Singleton design pattern. The Singleton pattern ensures that only one instance of a class can exist. By making the constructor private, the class itself controls the creation of its own instance, allowing only a single instance to be created.

3. Factory Methods: Private constructors can be used in conjunction with factory methods. A factory method is a static method within the class that creates and returns instances of the class. By making the constructor private and providing a factory method, the class can control the object creation process and enforce any necessary rules or conditions.

4. Preventing Object Creation: Private constructors are often used to prevent the creation of objects for utility classes or classes that provide only static methods. Since these classes do not require object instances, making the constructor private prevents accidental object creation and enforces the proper usage of the class.

5. Inheritance Restriction: When a class has a private constructor, it cannot be subclassed or inherited by other classes. The private constructor is not accessible in the subclass, preventing the creation of subclasses from outside the class.

6. Static Member Access: Even though a constructor is private, static members and methods of the class can still access the private constructor. This allows the class to create its own instances or control the creation of objects through internal static methods.

By making a constructor private, you have control over the object creation process and can enforce specific rules or patterns. It allows you to restrict object creation, implement design patterns like Singleton, or control the object instantiation process through factory methods. Private constructors provide an additional level of encapsulation and ensure that objects are created in a controlled and intentional manner.


In object-oriented programming, constructors cannot be directly overridden like regular methods. Overriding refers to the ability of a subclass to provide a different implementation for a method that is already defined in its superclass. Constructors, however, do not follow the same rules as regular methods when it comes to inheritance and overriding.

Here's why constructors cannot be overridden:

1. Inherited, Not Overridden: Constructors are not inherited like other class members. When you create a subclass, it does not inherit the constructor of its superclass. Instead, the subclass has its own constructors, and each constructor is responsible for initializing its own class and invoking a constructor in the superclass using the `super` keyword.

2. Name and Signature: Constructors have the same name as the class they belong to and do not have a return type. They are uniquely identified by their parameter list. When you create a constructor in a subclass, you are not overriding the constructor of the superclass; you are simply creating a new constructor in the subclass with the same or different parameter list.

3. Superclass Initialization: Constructors in a subclass have the responsibility to invoke a constructor in the superclass using the `super` keyword. This ensures that the superclass is properly initialized before the subclass-specific initialization takes place. The invocation of the superclass constructor is part of the subclass constructor's implementation and is not considered as method overriding.

4. Implicit Superclass Constructor: If the superclass does not have a default (parameterless) constructor, the subclass constructor must explicitly invoke a superclass constructor using `super` and provide the necessary arguments. This requirement further illustrates that constructors in the superclass and subclass are distinct and not overridden.

While constructors cannot be overridden, they do participate in the inheritance process. Subclass constructors invoke superclass constructors to ensure proper initialization and construction of the inheritance hierarchy.

To summarize, constructors in a subclass are not overridden but rather create new constructors within the subclass. The subclass constructors invoke the superclass constructors using `super` to initialize the inherited members and establish the inheritance relationship. Constructors play a critical role in the initialization and construction of objects, especially in the context of inheritance, but they do not follow the same rules as regular methods when it comes to inheritance and method overriding.