Constructor in Java

In this tutorial, we will learn about Constructor in Java. The constructor looks exactly the same as a normal method but there is some difference between constructor and method check these:

  • The contractor has no explicit return type
  • Name of constructor would same as class name
  • We can not make a constructor abstract, static, final, and synchronized

When we create a new object of class we call the constructor. The main motive of the constructor is to initialize an object and memory allocation of the object. for example, we are creating five objects of class it means we are calling the constructor for five times and we are allocating memory to each object.

I know a question is arising in your mind in the last tutorial there was no constructor in class then how our program was working and how we could create the object. It is so simple when we don’t create object compile it self create a default constructor compile time.

Types of Constructor

  • Default constructor (no-arg constructor)
  • Parameterized constructor

Default constructor:

Default constructor doesn’t takes any parameters. A Default constructor will initialize all the objects with same values.

public class DefaultExample {
   int var;
   public DefaultExample(){
        var=10;
   }

   public static void main(String args[]) {
      DefaultExample obj1 = new DefaultExample();
      DefaultExample obj2 = new DefaultExample();
      System.out.println(obj1.var + " " + obj2.var);
   }
}

It is important to note when we don’t create constructor in our class. Compiler itself create default constructor in class.

Parameterized constructor:

Parameterized constructor accept parameter. We can pass parameters to constructor while creating object of class.

public class ParaExample {
   int var;
   public ParaExample(int v){
        var=v;
   }

   public static void main(String args[]) {
      ParaExample obj1 = new ParaExample(10);
      ParaExample obj2 = new ParaExample(20);
      System.out.println(obj1.var + " " + obj2.var);
   }
}
Spread the love