Constructors in Java

Constructors are used to defining the object’s state. When we create an object of the class, the constructor is called automatically. It is named as a constructor, because it is used to construct the value or provide the data for the objects i.e. they are used to initialize the values for the objects. Every class has a constructor, if we do not declare a constructor then the default constructor is automatically called by the compiler.

Example

public class Hello {
	Hello() { // Constructor of the class
		System.out.println("Constructor Called");
	}
   public static void main(String args[]) {
		Hello obj1 = new Hello(); // object of the class is created
		System.out.println("Constructor Example");
	}
}

Rules for Constructor

  • Constructor name must be same as of class name
  • A constructor must not have a return type
  • The constructor can be private
  • A constructor is automatically called when an object of the class is created
  • It is always called before any method automatically by its own
  • A constructor cannot be static
  • It is executed only once for an object

Note: In Java, all numeric data members are by default initialized to Zero, boolean by false, Character by space and String by null.

Types of Constructor

The constructor is categorized into three types which are described below:

Java Constructor

  • Default constructor

    If we do not define any constructor then the compiler automatically calls a default one. Suppose we want to buy a car. It always comes with some predefined features,
    so if we just simply order a car we will get just only those features, like the other customers get,
    which defines the concept of the default constructor.

Example

public class Car {
	boolean Wheels, Sound_System;

	public static void main(String args[]) {
		Car Swift = new Car(); // object of car class is created
	                               // default constructor is called and default values 
                                       //are assigned to the variables.
		System.out.println("Wheels of the car is : " + Swift.Wheels); // wheels is of default value.
		System.out.println("Sound_Sytem of the car is : " + Swift.Sound_System); // Sound System is of default value
	}
}

Output

Wheels of the car is : false
Sound_Sytem of the car is : false
  • Non-Parametrized Constructor

    It also does not have any parameters. The default and non-parametrized works as same, the only difference is that default constructor is created and called implicitly by the compiler whether we define a constructor or not. While non-parametrized is explicitly defined by us.

Example

public class Car{
	String Wheels, Sound_System;

	Car() { // Non_Parametrize Constructor
		Wheels = "alloys";
		Sound_System = "false";
	}

	public static void main(String args[]) {
		Car Swift1 = new Car(); // object of car class is created//non-parameterized
					// constructor is called // and values are assigned to the// variables.
		System.out.println("Wheels of the car is : " + Swift1.Wheels); 
                                       // wheels is of default value for all objects explicitly declared by us
		System.out.println("Sound_Sytem of the car is : " + Swift1.Sound_System); 
                                      // Sound System is of default value for all objects explicitly declared by us
	}
}

Output

Wheels of the car is : alloys
Sound_Sytem of the car is : false

Explanation: Here we defined a non-parametrized constructor so the compiler will not call the default constructor, the non-parametrized will be called and the value of a will be set to 10,

  • Parametrized Constructor 

    A constructor having parameters is called as Parametrized Constructor. Parameterized Constructor is used to provide different values to different objects. In our previous example of the car if we need some extra features or we want to modify the features according to us like we want alloy wheels or extra sound system we can also do that and those features will be different for all customers which define the concept of the parameterized constructor.

Example

public class Car {
	String Wheels, Sound_System;

	Car(String Wheels, String Sound_System) {
		System.out.println("Wheels of my car is : " + Wheels);
		System.out.println("Sound_Sytem of my car is of : " + Sound_System);
	}

	public static void main(String args[]) {
		Car Swift1 = new Car("Alloys", "Sony"); // object of car class is created//parametrized constructor is called
			                                // and values are assigned to the variables.
	}
}

Output

Wheels of my car is : Alloys
Sound_Sytem of my car is of : Sony

Explanation: Firstly 10 is assigned to variable a when we create the first object i.e. obj1, then 20 is assigned when the second object i.e. obj2 is created.

  • Constructor Overloading

    We can also overload the constructors. Let’s take an example.

public class overloading {
	boolean Wheels, Sound_System;

	overloading() {
		System.out.print("Wheels of the car is : " + Wheels);
		System.out.println(", Sound_Sytem of the car is : " + Sound_System);
	}

	overloading(String Wheels, String Sound_System) {
		System.out.print("Wheels of the car is : " + Wheels);
		System.out.println(", Sound_Sytem of the car is : " + Sound_System);
	}

	overloading(String Sound_System) {
		System.out.print("Wheels of the car is : " + Wheels);
		System.out.println(", Sound_Sytem of the car is : " + Sound_System);
	}

	public static void main(String args[]) {
		overloading swift1 = new overloading("alloys", "sony"); //First object of class
		overloading swift2 = new overloading("samsung");        //Second object of class
		overloading swift3 = new overloading();                 //Third object of class
	}
}

Output

Wheels of the car is : alloys, Sound_Sytem of the car is : sony
Wheels of the car is : false, Sound_Sytem of the car is : samsung
Wheels of the car is : false, Sound_Sytem of the car is : false

Octocat - CodedBug github

Find the working example t codedbug GitHub repo

Most Frequently asked questions on Constructor in Java?

The return type is not allowed for a constructor to differentiate constructor block from method block.
No, we cannot have a constructor defined in an Interface.
Private constructors are used to restricting the instantiation of a class. When a class needs to prevent other classes from creating its objects then private constructors are suitable for that.
Different constructors can do different work by implementing the different line of codes and are called based on the type and number of parameters passed. In this way, constructor overloading helps.
The compiler won’t insert default no-arg constructor during the compilation process if a programmer defines constructor explicitly (whether it is default or parameterized constructor)