Constructor in Java with Examples

This article will discuss constructors in the Java programming language. We will cover topics such as what constructors are, the rules for creating them, the different types of constructors, and constructor overloading.

We will go over each section with a variety of programs to better grasp the concept. However, I strongly encourage you to practice the codes shown in the article and try some variations of the same codes to master the concept.

What is a Java Constructor?

A constructor is a special method that is used to create an object. It is called when an object is created, and it can be used to initialize the object’s state and values. When you create an object using the new keyword, the constructor is called. If you don’t specify a constructor, the Java compiler will create a default constructor for you.

A default constructor is used to assign default values, such as 0 or null, to the fields of a class. In addition to initializing the fields, a Java constructor can also perform other tasks, such as calling methods, creating objects, and starting threads. The Constructor class in Java can be used to get information about a constructor.

A constructor is very similar to a function except for just 2 differences. A method returns the current class instance, while a constructor does not have any explicit return type. A method is invoked implicitly, while a constructor is not.

Syntax of a constructor in Java

Before we proceed further and look at the rules of writing a constructor and the types, let us take a moment to discuss the syntax of a constructor.

class <className>
{
<className>()
{ 
<body of constructor>
}
}

You must remember that the name of teh constructor is the same as that of the class name. Here is an example to better understand:

class FirstCode 
{
    FirstCode()//Constructor
    {
        System.out.println("Constructor is called");
    }
    public static void main(String[] args)
    {
        FirstCode FC = new FirstCode();
    }
}

Output:

Constructor is called

Before we proceed to the next topic, let us take a brief moment to understand when exactly constructors are invoked in a program. We saw that methods and constructors are very similar, and we know that methods are invoked when we call them. But we are not explicitly calling constructors anywhere, so how are they invoked?

Whenever an object is created using the new() keyword, the constructor for that object is called to initialize its data members. In other words, when an object is instantiated, its constructor is invoked.

Some points to remember while writing constructors:

While writing or declaring constructors, you need to remember a few points:

1. The name of the constructor and the name of the class must be exactly the same. Moreover, the constructor must be enclosed in the class.

2. Unlike a method, a constructor cannot be abstract, synchronized, static, or final.

3. We can use access specifiers while declaring a constructor to control its access. This helps us specify which other class can access the constructor.

Various types of constructors in Java

In Java, there are 3 types of constructors; let us take a look at them in detail.

1. Java Default constructor

A constructor without parameters is known as a default constructor. A default constructor is implicit and does not need to be declared.

A constructor without arguments is not a default constructor, but a parameterized constructor. The compiler will overload it if there is already a constructor with arguments.

The default constructor was replaced by the parameterized constructor. However, the parameterized constructor cannot alter the default constructor.

Here is an example showcasing a default constructor:

class FirstCode 
{
    FirstCode() 
    { 
        System.out.println("Default constructor invoked"); 
    }
     public static void main(String[] args)
    {
        FirstCode FC = new FirstCode();
    }
}

Output:

Default constructor invoked

2. Java Parameterized constructor

A constructor with parameters is called a parameterized constructor. It is used to initialize the fields of a class with our own values.

Here is an example illustrating how parameters can be initialized using the parameterized constructor:

class FirstCodeEmployee 
{
    String emp_name;
    int emp_id;
    FirstCodeEmployee(String name, int id)
    {
        System.out.println("Parameterized  constructor invoked");
        this.emp_name = name;
        this.emp_id = id;
    }
}
class FirstCode {
    public static void main(String[] args)
    {
        FirstCodeEmployee emp1 = new FirstCodeEmployee("Gopi Kiran", 21023);
        System.out.println("Employee details: \nEmployee name is " + emp1.emp_name + ", and employee Id is :" + emp1.emp_id);
    }
}

Output:

Parameterized constructor invoked
Employee details:
Employee name is Gopi Kiran, and employee Id is 21023

3. Java Copy constructor

A copy constructor is a special type of constructor that is called when a new object is created by copying the data from an existing object.

Here is an example showing the same:

class FirstCodeEmployee 
{
    String emp_name;
    int emp_id;
    FirstCodeEmployee(String name, int id)
    {
        System.out.println("Parameterized  constructor invoked");
        this.emp_name = name;
        this.emp_id = id;
    }
    FirstCodeEmployee(FirstCodeEmployee emp2)
    {
        System.out.println("Copy  constructor invoked");
        this.emp_name = emp2.emp_name;
        this.emp_id = emp2.emp_id;
    }
}
class FirstCode {
    public static void main(String[] args)
    {
        FirstCodeEmployee emp1 = new FirstCodeEmployee("Gopi Kiran", 21023);
        System.out.println("Employee details: \nEmployee name is " + emp1.emp_name + ", and employee Id is :" + emp1.emp_id);
        FirstCodeEmployee emp2 = new FirstCodeEmployee(emp1);
        System.out.println("Employee name is " + emp2.emp_name + ", and employee Id is :" + emp2.emp_id);

    }
}

Output:

Parameterized constructor invoked
Employee details:
Employee name is Gopi Kiran, and employee Id is 21023
copy constructor invoked
Employee name is Gopi Kiran, and employee Id is 21023

Can we copy values without using a constructor in Java?

Yes, simply yes. Here is an example showing that we can still copy values without the use of a copy constructor:

class FirstCodeEmployee
{  
    int emp_id;  
    String emp_name;  
    FirstCodeEmployee(){}
    FirstCodeEmployee(int i,String n)
    {  
        emp_id = i;  
        emp_name = n;  
    }  
    void display()
    {
        System.out.println("Employee name is " + emp_name + ", and employee Id is :" + emp_id);
    }  
    public static void main(String args[])
    {  
        FirstCodeEmployee e1 = new FirstCodeEmployee(21213,"Gopi Kiran");  
        FirstCodeEmployee e2 = new FirstCodeEmployee();  
        e2.emp_id=e1.emp_id;  
        e2.emp_name=e1.emp_name;  
        e1.display();  
        e2.display();  
   }  
}

Output:

Employee name is Gopi Kiran, and employee Id is 21023
Employee name is Gopi Kiran, and employee Id is 21023

What does the term constructor overloading mean?

Constructor overloading is the process of creating multiple constructors with the same name but different parameters. This allows you to create different constructors that can be used to initialize objects with different data.

For more information on constructor overloading, please refer to our in-depth article on constructor overloading.

However, here is a code that illustrates constructor overloading:

class Main 
{
  String language;
  Main(){this.language = "Java";}
  Main(String language){this.language = language;}
  public void getName() 
  {System.out.println("Language: " + this.language);}
  public static void main(String[] args) 
  {
    Main obj1 = new Main();
    Main obj2 = new Main("Python");
    obj1.getName();
    obj2.getName();
  }
}

Output:

Language: Java
Language: Python

In the code shown above, we have 2 constructors, one with no input parameters, and the other with one input parameter. Based on the input, the respective constructor is invoked.

Before we end the discussion, let us take a look at a table shows the default values that are initialized by the constructor to any uninitialized instance variables.

Type Default Value
boolean false
byte 0
short 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
object Reference null

Conclusion

You have now learned about constructors in detail. In this article, we have discussed the syntax of constructors in Java, some key points to remember while declaring constructors, and the different types of constructors with the help of many programs to help you understand the concept better.

Leave a Reply

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