AppDividend
Latest Code Tutorials

Java Constructor Tutorial With Example | Constructor in Java

0

Java Constructor Tutorial With Example | Constructor in Java is today’s topic. A constructor is a code of blocks in java like methods. It is called when an object instance is created, and memory is allocated for the object. We can say Constructor is a particular type of method by which we can initialize the object of the class. It constructs the values at the time of a creation of an object that’s why is it called the Constructor. It is not mandatory to create the constructor for a class. Because at the compile time constructor is created by default if there is no constructor in the class.

Java Constructor Tutorial

Every time an object is created using the new() keyword, at least one constructor is called. It calls a default constructor. It is called the constructor because it constructs the values at a time of the object creation.

It is not necessary to write a constructor for the class. It is because java compiler creates a by default constructor if your class doesn’t have any constructor.

constructor is a special method that 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.

Java Constructor Tutorial

 

The constructor has the same name as the class and looks like this in java code.

public class Acme {

   //This is the constructor
   Acme(){

   }
   ..
}

One thing to note that the constructor name matches with the class name and it doesn’t have a return type.

Simple Constructor Program in Java

See the following code.

// Scan.java

public class Scan {
  String hero;

  // Constructor
  Scan() {
    this.hero = "Ironman";
  }

  public static void main(String[] args) {
    Scan obj = new Scan();
    System.out.println(obj.hero);
  }
}

When you run the above code, it will return the output as “Ironman.”

Some important rules for creating any constructor

  1. Constructor name must be same as the class name.
  2. It must not have any return value explicitly.
  3. A java constructor cannot be abstract, final and synchronized.
  4. Every class has the constructor whether it’s a regular class or an abstract class.
  5. If you don’t implement any constructor within the class, the compiler will do it for you.
  6. Constructor overloading is possible but overriding is not possible. Which means we can have the overloaded constructor in our class, but we can’t override a constructor.
  7. If Superclass doesn’t have a no-arg(default) constructor, then the compiler would not insert a default constructor in a child class as it does in a standard scenario.
  8. Interfaces do not have constructors.
  9. A constructor can also invoke another constructor of the same class. By using this(). If you want to invoke the parameterized constructor, then do it like the following: this(parameter list).
  10. Constructors cannot be inherited.

Note: We can use access modifier while creating any constructor to control object creation. We can use public, private, default or protected as access modifier in Java.

Types of Constructor

There are two types of a constructor. We will discuss this one by one.

  1. Default Constructor (No arguments)
  2. Parameterized constructor

Default Constructor

The default constructor initializes the default values of objects. And this constructor doesn’t take any parameter. It invokes the object creation.

Syntax

<Class name> () {}

See the following code example.

// Box.java

class Box
{
	//default constructor 
	Box()
	{
		System.out.println("Constructor for Box class have been created");
	}
	public static void main(String [] ar)
	{
		//invoking constructor while initializing object 
		Box b= new Box();
	}
}

The output is following.

Default Constructor in Java

 

Why we use default constructor?

We use the default constructor to provide default values (0, null, etc.) to objects.

Let see an example to understand this correctly.

// DefaultCons.java

//default constructor which displays the default values  
class DefaultCons
{  
  int length;  
  String name;

  //method to display the value of id and name  
  void display()
  {
	System.out.println(length+" "+name);
  }  
  
  public static void main(String args[])
  {  
	//creating objects  
	DefaultCons d1=new DefaultCons();  
	DefaultCons d2=new DefaultCons();  
        
        //displaying values of the object  
	 d1.display();  
	 d2.display();  
    }  
}

The output is following.

Why we use default constructor?

 

In the above class, we are not creating any constructor, so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.

Parametrized Constructor

A constructor which contains parameters is known as Parameterized constructor. It is used to provide different values to distinct objects.

Let’s see an example we will create a class and then a parameterized constructor then we will initialize values to the objects.

// Student.java

//Java Program to demonstrate the use of parameterized constructor  
class Student
{  
    int id;  
    String name;  
    
   //creating a parameterized constructor  
    Student(int id,String name)
    {  
      this.id = id;  
      this.name = name;  
    }  
    //method to display the values  
    void show()
    {
	System.out.println(id+" "+name);
    }  
   
    public static void main(String args[])
    {  
        //creating objects and passing values  
        Student s1 = new Student(100,"Ram");
        Student s2 = new Student(200,"Rahim");  
        //calling method to display the values of object  
        s1.show();  
        s2.show();  
    }  
}

See the following output.

Parametrized Constructor in Java

 

Constructor Overloading

Java constructor is like methods but without return type.

So, it can be overloaded like conventional methods.

Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. The compiler differentiates them by the number of parameters in the list and their types.

See the following code.

// Student2.java

//Java program to overload constructors in java  
class Student2
{  
    int id;  
    String name;  
    int age;  
    //creating two arg constructor  
    Student2(int id,String name)
    {  
       this.id = id;  
       this.name = name;  
    }
    //creating three arg constructor  
    Student2(int id,String name,int age)
    {  
       this.id = id;  
       this.name = name;  
       this.age=age;  
    }  
    void show()
    { 
	System.out.println(id+" "+name+" "+age);
    }  
   
    public static void main(String args[])
    {  
        Student2 s1 = new Student2(100,"Ram");
        Student2 s2 = new Student2(200,"Rahim",18);
        s1.show();
        s2.show();
    }  
}

See the below output.

Constructor Overloading

 

Java Copy Constructor

There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are following.

  1. By constructor
  2. By assigning the values of one object into another

Example1: Here, we are going to copy the values of one object into another using java constructor.

// Student3.java

//Java program to initialize the values from one object to another class Student3
{  
    int id;  
    String name;  
    //constructor to initialize integer and string  
    Student3(int id,String name)
    {  
       this.id = id;  
       this.name = name;  
    }  
    //constructor to initialize another object  
    Student3(Student3 s)
    {  
       this.id = s.id;  
       this.name = s.name;  
    }  
    void show()
    {
	 System.out.println(id+" "+name);
    }  
   
    public static void main(String args[])
    {  
        Student3 s1 = new Student3(100,"Ram");  
        Student3 s2 = new Student3(s1);  
        s1.show();  
        s2.show();  
    }
}

The output is following.

Java Copy Constructor

 

Example2: We can copy the values of one object into another by assigning the values of the object to another object. In this case, there is no need to create the constructor.

See the following code.

// Student4.java

class Student4
{  
    int id;  
    String name;  
    Student4(int id,String name)
    {  
       this.id = id;  
       this.name = name;  
    }  
    Student4()
    {
		
    }  
    void show()
    {
       System.out.println(id+" "+name);
    }  
   
    public static void main(String args[])
    {  
       Student4 s1 = new Student4(100,"Ram");  
       Student4 s2 = new Student4();
       s2.id=s1.id;
       s2.name=s1.name;  
       s1.show();  
       s2.show();  
    }  
}

The output is following.

Java Constructor example

 

Difference between Constructor and Method

  1. The purpose of a constructor is to initialize the object of the class while the purpose of a method is to perform the task by executing the java code.
  2. Constructors cannot be abstract, final, static and synchronized while methods can be abstract, final, static, and synchronized.
  3. Constructors do not have the return types while methods do.

Finally, Java Constructor Tutorial With Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.