Java Constructor


What is Constructor?

A constructor is a type of special member function that is primarily used to initialize class data members.


Why would we use a constructor?


Constructor Writing Rules

public class Main
{
  public Main ()
  {
      System.out.println("Constructor");
  }
  public static void main (String[]args)
  {
    Main m1=new Main();
  }
}

Types of constructors

There are two types of constructors available in Java.

  1. Non-Parameterized Constructor(Default/void constructor)
  2. Parameterized Constructor

Non-Parameterized Constructor

Non-Parameterized Constructor does not contain any parameters or arguments, hence it is also called void constructor. This constructor is in Java by default so it is also called default constructor. The following is an example from this constructor.

Program
public class Main
{
  public Main ()  //non-parameterized constructor
  {
      System.out.println("Default Constructor");
  }
  public static void main (String[]args)
  {
    Main m1=new Main();  
  }
}
Run

Parameterized Constructor

If a parameter or a list of parameters is sent through the constructor, it is called a Parameterized Constructor.

Program
public class Main
{
    int _a;
    int _b;
    public Main(int a, int b)
    {
        this._a=a;
        this._b=b;
    }
    public void Sum()
    {
        int sum=this._a+this._b;
        System.out.println("a+b = "+sum);
    }
	public static void main(String[] args) 
	{
		Main obj=new Main(10,20);
		obj.Sum();
	}
}
Run

Constructor Overloading

In Java, a constructor is just like a method but without any return type. It can also be overloaded like the Java method.

Constructor overloading in Java is a strategy of having multiple constructors with a list of different parameters. These are arranged in such a way that each builder performs different tasks. They are separated by the compiler by the number of parameters in the list and their type.

Program
public class Main
{
  String _name;
  int _roll;
  int _marks;
  String _grade;
  public Main (String name, int roll, int marks)
  {
    this._name = name;
    this._roll = roll;
    this._marks = marks;
  }
  public Main (String name, int roll, int marks, String grade)
  {
    this._name = name;
    this._roll = roll;
    this._marks = marks;
    this._grade = grade;
  }
  public void Show ()
  {
    System.out.println (this._name + " " + this._roll + " " + this._marks +" " + this._grade);
  }
  public static void main (String[]args)
  {
    Main obj = new Main ("Chandan", 1, 98);
    Main obj1 = new Main ("Ritu", 2, 75, "A");
    obj.Show();
    obj1.Show();
  }
}
Run