Java

Constructors In Java

A section of code called the constructor initializes a freshly generated object. In Java, a constructor is similar to an instance method, but since it lacks a return type, it is not a method. Constructor and method are distinct, to put it simply (More on this at the end of this guide). Constructor is sometimes referred to as a specific form of Java method.

Constructors in Java code have the same name as the class and look like this.

public class MyClass{
   //This is the constructor
   MyClass(){
   }
   ..
}

How does a constructor work

Let’s use an example to better comprehend how a constructor works. Suppose we have a class called MyClass.
When we build the MyClass object in the following manner:

MyClass obj = new MyClass()

Here, the new keyword creates an object of the MyClass class and calls the constructor to initialize it.

Since I haven’t given you any initialization examples, you could get a bit confused here. Let’s look at the code below:

A simple constructor program in java

Here we have created an object obj of class Hello and then we displayed the instance variable name of the object. As you can see that the output is BeginnersBook.com which is what we have passed to the name during initialization in constructor. This shows that when we created the object obj the constructor got invoked. In this example we have used this keyword, which refers to the current object, object obj in this example. We will cover this keyword in detail in the next tutorial.

public class Hello {
   String name;
   //Constructor
   Hello(){
      this.name = "BeginnersBook.com";
   }
   public static void main(String[] args) {
      Hello obj = new Hello();
      System.out.println(obj.name);
   }
}

Output:

BeginnersBook.com

Types of Constructors

There are three types of constructors: Default, No-arg constructor and Parameterized.

Default constructor

Java compiler automatically inserts a default constructor into your code if you don’t implement any constructors in your class. The term “default constructor” refers to this constructor. As it would be put into the code during compilation and live in a.class file, you would not locate it in your source code (the java file). The graphic below depicts this procedure:

no-arg constructor:

No-arg constructor is a constructor that accepts no parameters. Although the body may contain any code, unlike the default constructor, which has an empty body, the signature is the same.

Example: no-arg constructor

class Demo
{
     public Demo()
     {
         System.out.println("This is a no argument constructor");
     }
     public static void main(String args[]) {
    	 new Demo();
     }
}

Output:
This is a no argument constructor

Parameterized constructor

Constructor with arguments(or you can say parameters) is known as Parameterized constructor.

Example: parameterized constructor

In this example, the constructor has two parameters: id and name. I gave two parameters while generating the objects obj1 and obj2 so that this constructor is called after obj1 and obj2 have been created.

public class Employee {

   int empId;  
   String empName;  
	    
   //parameterized constructor with two parameters
   Employee(int id, String name){  
       this.empId = id;  
       this.empName = name;  
   }  
   void info(){
        System.out.println("Id: "+empId+" Name: "+empName);
   }  
	   
   public static void main(String args[]){  
	Employee obj1 = new Employee(10245,"Chaitanya");  
	Employee obj2 = new Employee(92232,"Negan");  
	obj1.info();  
	obj2.info();  
   }  
}

Output:

Id: 10245 Name: Chaitanya
Id: 92232 Name: Negan

Example2: parameterized constructor

In this illustration, there are two constructors: a parameterized constructor and a default constructor. When we use the new keyword to create an object, the default constructor is called when no parameters are supplied; however, when a parameter is passed, the parameterized constructor that corresponds to the passed parameters list is used.

class Example2
{
      private int var;
      //default constructor
      public Example2()
      {
             this.var = 10;
      }
      //parameterized constructor
      public Example2(int num)
      {
             this.var = num;
      }
      public int getValue()
      {
              return var;
      }
      public static void main(String args[])
      {
              Example2 obj = new Example2();
              Example2 obj2 = new Example2(100);
              System.out.println("var is: "+obj.getValue());
              System.out.println("var is: "+obj2.getValue());
      }
}

Output:

var is: 10
var is: 100

What if you implement only parameterized constructor in class

class Example3
{
      private int var;
      public Example3(int num)
      {
             var=num;
      }
      public int getValue()
      {
              return var;
      }
      public static void main(String args[])
      {
              Example3 myobj = new Example3();
              System.out.println("value of var is: "+myobj.getValue());
      }
}

Output:

A compilation error will be thrown. The explanation is because the line Example3 myobj = new Example3() calls a constructor that isn’t available in our application, the default constructor. The default constructor is inserted into your code by the compiler if you don’t implement any constructors in your class; however, if you do (as in the example above where I implemented a parameterized constructor with an int parameter), the compiler won’t insert the default constructor into your code.

The program would function correctly if the parameterized constructor from the previous code were removed since the compiler would then put the default constructor into your code.

Constructor Chaining

Constructor chaining occurs when one constructor calls another of the same class. To learn more, click here.

Super()

Every time the constructor of a child class is called, the constructor of the parent class is also called implicitly. You might alternatively argue that the super(); line is added by the compiler at the start of the child class constructor.

class MyParentClass {
   MyParentClass(){
	System.out.println("MyParentClass Constructor");
   }
}
class MyChildClass extends MyParentClass{
   MyChildClass() {
	System.out.println("MyChildClass Constructor");
   }
   public static void main(String args[]) {
	new MyChildClass();
   }
}

Output:

MyParentClass Constructor
MyChildClass Constructor

Constructor Overloading

Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task.

Refer constructor overloading with example for more details with example.

Java Copy Constructor

To duplicate the values of one object to another, use the copy constructor. Although Java lacks the copy constructor idea seen in C++, there are still a few techniques to replicate an object’s data to another object:

  • By designing a constructor with a class reference as an argument.
  • By using the Object class’s clone() function.
  • By the assignment of values from one object to another.
class JavaExample{  
   String web; 
   JavaExample(String w){  
	web = w;
   }  

   /* This is the Copy Constructor, it 
    * copies the values of one object
    * to the another object (the object
    * that invokes this constructor)
    */
   JavaExample(JavaExample je){  
	web = je.web; 
   }  
   void disp(){
	System.out.println("Website: "+web);
   }  

   public static void main(String args[]){  
	JavaExample obj1 = new JavaExample("BeginnersBook");  
		
	/* Passing the object as an argument to the constructor
	 * This will invoke the copy constructor
	 */
	JavaExample obj2 = new JavaExample(obj1);  
	obj1.disp();  
	obj2.disp();  
   }  
}

Output:

Website: BeginnersBook
Website: BeginnersBook

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button