Constructors in Java

A constructor is just like a method but has many features and differences to the method, that the name of the method must be the same as the name of the class and it doesn't return any value. The constructor is used to initialize a newly created object and is called just after the memory is allocated for the object. It can be used to initialize the objects to desired values or default values at the time of object creation. It is not mandatory for the developer to write a constructor for a class. If we do not define any constructor in a class, compiler initializes the member variable to its default values.

  • Numeric data types are set to 0.

  • Char data types are set to the null character.

  • Reference variables are set to null.

Rules for Creating a Constructor

  1. It has the name as the class name.
  2. It does not return any value not even void.
public class Employee{
	Employee () { // Constructor Declaration
		.... //Constructor body
	}
}

How Does Constructor Work

To understand the working of the constructor, let’s take an example. Let’s say we have a class Employee and when we create the object of Employee

Employee emp = new Employee();

The new keyword here creates the object of class Employee and invokes the constructor to initialize the newly created object.

A Simple program to understand the working of the constructor

public class Color {
   String colorName;
   //Constructor
   Color(){
      this.colorName = "Black";
   }
public static void main(String[] args) {
Color color = new Color();
 System.out.println(color. colorName);
   }
}
Example Output

Here we have created an object color of class Color and then we displayed the member variable which we do not initialize but we can see that the output is Black which is initialized by the constructor. So here we can see that whenever we create an object it calls the constructor to initialize the state of the object.

Types of Constructor in Java

There are two types of constructors in Java

Constructors in Java | Java Constructor Example

  • Default constructor (no-arg constructor)

  • Parameterized constructor

Default Constructor in Java

If we do not implement any constructor in our class, Java compiler inserts a default constructor into the code. This constructor is known as the default constructor. We would not find it in the source code (the java file) as it would be inserted into the code during compilation and exists in .class file.

For Example

public class Color {
 String colorName;
public static void main(String[] args) {
Color color = new Color();
}
}

In the above code, we are not declaring any constructor, but still, we are able to create the object, which means the class has a default constructor.

If we are implementing any constructor in class then there will be no default constructor in the class.

No-arg constructor – If we are implementing a constructor without arguments in our code, the constructor is known as a No-arg constructor. The signature is the same as the default constructor however the body can have any code, unlike the default constructor where the body of the constructor is empty.

Although sometimes we may get confused that default and the no-arg constructor is the same in fact, they are not, even if you write public Color() { } in the class Color it cannot be called a default constructor since we have written the code of it.

For Example

public class Color {
   String colorName;
Color()
public static void main(String[] args) {
Color color = new Color();
   }
}


2. Parameterized Constructor in Java

If we are implementing a constructor with parameters (arguments we can say) in our code, the constructor is known as a Parameterized constructor. This type of constructor is mainly used to initialize the constructor at runtime by passing the values while creating the object.

public class Color {
   int colorCode;  
   String colorName;  
   Color (int colorCode, String colorName){  
//parameterized constructor with two parameters
       this. colorCode = colorCode;  
       this. colorName = colorName;  
   }  
public String toString(){
        return "[Color Code: "+ colorCode +" Color Name: "+ colorName+ "]";
   }    
public static void main(String args[]){  
	Color color1= new Color (101,"Black");  
	Color color2 = new Color (102,"Blue");  
	System.out.println(color1);
	System.out.println(color2);  
   }  
}
Example Output

Here in the above example, we can see that while creating the object of Color we are passing the values in the constructor to initialize the object, and when we are printing the value it displays.

What if we implement only parameterized constructor in the class

If we are not implanting any type of constructor in a class, the compiler will create for us a default constructor as we have seen in the last example. But what if we have declared a parameterized constructor and we are calling a default constructor.

Look into the below example-

public class Color {
   int colorCode;  
   String colorName;  
   Color (int colorCode, String colorName){  
//parameterized constructor with two parameters
       this. colorCode = colorCode;  
       this. colorName = colorName;  
   }  
public String toString(){
        return "[Color Code: "+ colorCode +" Color Name: "+ colorName+ "]";
   }    
public static void main(String args[]){  
	Color color1= new Color ();  
	Color color2 = new Color ();  
	System.out.println(color1);
	System.out.println(color2);  
   }  
 }


Output: It will throw a compilation error.

The reason is the statement Color color1= new Color () is trying to invoke a default constructor that we don’t have in our program. So when we implement any constructor (in the above example I have implemented a parameterized constructor with two parameters), then we don’t receive the default constructor by the compiler into our code.

If we remove the parameterized constructor from the above code then the program would run fine, because then the compiler would insert the default constructor into our code.

Share