dsa

Java Constructor

Introduction :

In this tutorial, you'll learn about Java constructors, how to create and use them, and different types of constructors with the help of examples.

What is a Constructor ?

Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation. A Java method and Java constructor can be differentiated by its name and return type. A constructor has the same name as that of class and it does not return any value.

Syntax :


class CodeMistic 
{
	CodeMistic() 
	{
	        // constructor body
	}
}

Here, CodeMistic() is a constructor. It has the same name as that of the class and doesn't have a return type.

For Example :


class CodeMistic 
{
   	private int x;

   	// constructor
   	private CodeMistic()
	{
       		System.out.println("Constructor Called .");
		x=5;
   	}

   	public static void main(String[] args)
	{
       		// constructor is called while creating object
       		CodeMistic obj = new CodeMistic();
       		System.out.println("Value of x = " + obj.x);
   	}
}
Output :

Constructor Called .
Value of x = 5

Types of Constructor :

There are three types of constructor in Java:

Constructor Overloading in Java

Like methods, we can overload constructors for creating objects in different ways. Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters and order of the parameters.

Example :


class Company 
{

    	String domainName;

    	// constructor with no parameter
    	public Company()
	{
        	this.domainName = "default";
    	}

    	// constructor with single parameter
    	public Company(String domainName)
	{
	        this.domainName = domainName;
    	}

    	public void getName()
	{
        	System.out.println(this.domainName);
    	}

    	public static void main(String[] args) 
	{
	        // calling the constructor with no parameter
	        Company defaultObj = new Company();
	
        	// calling the constructor with single parameter
        	Company CodeMisticObj = new Company("codemistic.in");

        	defaultObj.getName();
        	CodeMisticObj.getName();
    	}
}

Output :


default
codemistic.in