What is a constructor in oop?

Learnwithshikha
2 min readMay 22, 2021

In OOP(Object-oriented programming) constructor is a special method. It is called whenever you create an object using new keyword. Constrictor 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

  • A constructor always has the same name as the class whose instance members they initialize.
  • 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.

Syntax for Constructor

constructorName([parameterList])

{

//constructor body

}

  • Here, the constructorName is the same as the class name it belongs to.
  • The parameterList is the list of optional zero or more parameters that are specified after the classname in the parentheses.

Create Constructor:

// Create a Main class
public class Main {
int x;
// Create a class constructor for the Main class
public Main() {
x = 5;
}
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}

Output:

5

Constructor in OOP:

There are two types of Constructor

  1. Default Constructor
  2. Parameterized Constructor

For more detailed information please click here.

Hope this helps. Thank you

--

--

Learnwithshikha

Hi, This is Shikha from India. I’m working as front-end developer besides a blogger. Here is my website https://learnwithshikha.com/