This tutorial will discuss Java Constructor, its types and concepts like constructor overloading and constructor chaining with code examples:
From our earlier tutorials, we know that the instance of a class is called an object. An object of a class is created by using the “new” keyword. A special method called “constructor” is called when we create an object with a new keyword or when the object is instantiated.
A constructor is defined as a block of code to initialize the class object. It is identical to the method but it is not a method. However, it can be termed as a “special method” in Java.
=> Check Here To See A-Z Of Java Training Tutorials Here.
Table of Contents:
Java Constructor
Java constructor is used to initialize the object just created. An object needs to have some data before it is used in the program. Hence we use constructor so that we can assign some initial data to the object.
As a simple example, consider a class ABC for which we need to create an object. Let’s create an object ‘myObj’ for the class ABC using a new keyword.
ABC myObj = new ABC ();
The above statement creates an object myObj. When this object is being created, a constructor for class ABC with no argument is called (ABC () depicts that there are no arguments for the constructor). As there are no arguments provided for the above constructor, the member fields of the myObj will be initialized to their default initial values.
For example,
- Numeric data types like int are set to 0.
- Char data type variable value is set to null (‘\0’) character.
- References are set to null.
In this tutorial, we will discuss the constructors in detail along with the various constructors used in Java.
How To Create A Constructor In Java
To create a constructor in Java, we need to follow certain rules as given below.
- The class constructor has the same name as that of the class.
- There cannot be a constructor that is final, abstract, synchronized, or static. This is because the Final acts as a constant, abstract cannot be instantiated. While synchronized is used in the case of multi threading, and the static keyword is used at the class level.
- We can use access modifiers with the constructors.
- A constructor cannot have a return type.
For example, let’s define a class Student as follows:
class Student{ String name; int roll_no; }
We can create objects of the above class using the new keyword. While the object is being created, we can initialize the two-member variables of this class by providing a constructor. Note that even if we do not provide a constructor and just execute the below statement,
Student student = new Student ();
Still, Java will execute a default constructor that will initialize the two-member variables to their system defaults. Now, if we want the initial value of Student.name to be “Keith” and roll_no to be 27, then to do this we can create the following constructor method.
Student () { name = "Keith"; roll_no = 27; }
When we create an object of the student class with the below statement
Student student = new Student ();
Then the initial values of the member variables name and roll_no will be Keith and 27 respectively.
Now that a constructor is created, when it will be called?
A constructor is called each time when an object is created with the new keyword as in the above case. As already mentioned, if no constructor is provided, Java provides a default constructor that is called when the object is created using the new keyword.
Constructor Example
The following program shows a constructor example in which we have a simple constructor without any arguments. This constructor simply assigns initial values to its member variables.
//class definition class classDemo{ int num1; int num2; //constructor classDemo(){ num1 = 100; num2 = 250; System.out.println("Inside ClassDemo::Constructor"); } public void display(){ System.out.println("num1 = "+ num1); System.out.println("num2 = "+ num2); } } class Main{ public static void main(String args[]){ classDemo cd1 = new classDemo(); //create object of ClassDemo cd1.display(); } }
Output:
Default Constructor In Java
The default constructor is also called the Empty Constructor. This constructor is inserted by the Java compiler into the class code where there is no constructor implemented by the programmer. Default constructor is inserted during compilation and hence it will appear only in ‘.class’ file and not in the source code.
Consider the following Java class.
source file (.java) class file (.class)
In the above figure, the first figure shows the source code wherein we have not specified any constructor. So when we compile this code and the .class file is generated, we can see that the Java compiler has inserted a default constructor as shown in the adjoining figure (in blue color).
Note:
Sometimes a default constructor is used to describe no-arg constructor in Java. But these two terms are different in reality. No-arg constructor is a type of constructor in Java that is specified by the programmer. The default constructor is the constructor that is inserted by the Java compiler.
Hence although these two terms are used interchangeably by most of the programmer, it is advisable not to confuse these two terms.
When Java inserts a default constructor, if the program has any variables, then they are assigned the default values.
The below table shows the default values of each data type.
Type | Default value |
---|---|
Object | Reference null |
boolean | false |
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
char | \u0000 |
float | 0.0f |
double | 0.0d |
The following program gives an example of a default constructor in Java.
class Main { int num; boolean flag; public static void main(String[] args) { // A default constructor is called Main obj = new Main(); System.out.println("num:default value = " + obj.num); System.out.println("flag:default value = " + obj.flag); } }
Output:
Types Of Constructors In Java
There are two types of constructors in Java as shown below.
#1) No-arg Constructor
A constructor without any arguments is called no-args or no-argument constructor. If we do not have a constructor without any arguments, then the Java compiler does not create a default constructor for the class.
In general, if we define a constructor in our class, then the default constructor is not inserted by the Java compiler.
Given below is an example of the No-arg Constructor
import java.io.*; class DemoClass { int num; String name; // no-args Constructor called when object is created DemoClass() { System.out.println("DemoClass::Constructor called"); System.out.println("Initial member variable values:"); System.out.println("num = " + num + " name = " + name); } } class Main{ public static void main (String[] args) { // this will invoke no-args Constructor DemoClass dc1 = new DemoClass(); } }
Output:
In this program, we have provided a no-args constructor. Here, we print some messages including the member variables. We can see in the output that the messages from the constructor are displayed indicating that the no-args constructor is executed.
#2) Parameterized Constructor
A parameterized constructor has one or more parameters. We can use a parameterized constructor in case we need to pass some initial values to the member variable of the class.
import java.io.*; class DemoClass { // data members of the class. String name; int id; // parameterized constructor called when object is created DemoClass(String name, int id) { this.name = name; this.id = id; } } class Main { public static void main (String[] args) { // this will invoke the parameterized constructor. DemoClass dc1 = new DemoClass("Java", 1); System.out.println("Tutorial Name :" + dc1.name + ", Id :" + dc1.id); } }
Output:
Here we have provided a parameterized constructor that takes two arguments i.e. name and id.
Inside the constructor body, the arguments are assigned as values to the member variables name and id respectively.
Then in the main method when we create a new object using the new keyword, we pass two values to the class name following a new keyword. This indicates that we are calling the parameterized constructor. When we display the member variables, we can see that they have the values that we passed while creating the object.
Overloaded Constructors In Java
Now the question arises as whether a class can have more than one constructor or is it that a class can have only one constructor?
Well, we can have multiple constructors in a class. A class can have as many constructors in it as long as they are properly overloaded.
So what is exactly meant by the Overloading of Constructors?
Constructor Overloading is a mechanism that allows a class to have as many constructors so that all these constructors have different parameter lists whether depending on parameter types or order of parameters.
The below program demonstrates the Constructor Overloading.
//class with multiple constructors class DemoClass{ int val1; int val2; //no args Constructor DemoClass(){ val1 = 10; val2 = 20; System.out.println("DemoClass:: No argument Constructor"); } //Overloaded Constructor DemoClass(int num1){ val1 = num1; val2 = num1; System.out.println("DemoClass:: Overloaded Constructor with one argument"); } //Overloaded DemoClass(int num1,int num2){ val1 = num1; val2 = num2; System.out.println("DemoClass:: Overloaded Constructor with two arguments"); } public void display(){ System.out.println("val1 === "+val1 + " ; val2 === "+val2 ); } } class Main{ public static void main(String args[]){ DemoClass d1 = new DemoClass(); //object with no-args Constructor d1.display(); DemoClass d2 = new DemoClass(10); //object with 1 arg Constructor d2.display(); DemoClass d3 = new DemoClass(20,40); //object with 2 arg Constructor d3.display(); } }
Output:
In the above program, we have a class containing three constructors. The first constructor is a no-arg constructor, and then we have one each with one argument and two arguments respectively. As the constructor has a unique parameter list, we can say that the constructors are overloaded.
‘this ()’ Constructor In Java
In a class containing multiple constructors, what if we want to call one constructor from another constructor in this class?
For this purpose, we use the keyword “this” inside the constructor from which we want to call another constructor.
So when a class has multiple constructors, a no-arg constructor, and a parameterized constructor, we use ‘this’ keyword to call a parameterized constructor from the no-args constructor. This is also called “Explicit invocation of constructor”.
Why do we need this keyword?
We need it because the explicit invocation of constructors is not possible directly by using only the constructor name.
Points to note:
- The keyword ‘this’ should be the first statement in the calling constructor.
- If a constructor has “this” keyword, then it cannot have “super”. This means that the constructor can have either super or this.
class TestClass { TestClass() { //calling Parameterized Constructor this("SoftwareTestingHelp"); System.out.println("TestClass::No-args Constructor"); } TestClass(String str) { System.out.println("TestClass:: Parameterized Constructor(String):" + str); } } class Main{ public static void main(String[] args) { TestClass obj = new TestClass(); } }
Output:
In the above program, we have a ‘TestClass’ with two constructors. We call this (“SoftwareTestingHelp”) from the no-args constructor. This is the explicit invocation of the parameterized constructor.
Copy Constructor In Java
We are aware of the copy constructor in C++. The copy constructor is a constructor that has an object reference as an argument and a new object is created using the data of the reference object.
C++ provides a default copy constructor if one is not provided in the program.
Java also provides support for copy constructor, but it does not provide a default copy constructor.
The following Java program demonstrates the copy constructor using the classic example of complex numbers that have real and imaginary components.
class Complex { private double real, imaginary; // parametrized constructor public Complex(double real, double imaginary) { System.out.println("Complex:: parametrized constructor"); this.real = real; this.imaginary = imaginary; } // copy constructor Complex(Complex c) { System.out.println("Complex::Copy constructor called"); real = c.real; imaginary = c.imaginary; } // Overriding the toString of Object class @Override public String toString() { return "(" + real + " + " + imaginary + "i)"; } } public class Main { public static void main(String[] args) { Complex c1 = new Complex(1, 5); //calls parametrized constructor System.out.println("C1 = " + c1); // copy constructor called Complex c2 = new Complex(c1); System.out.println("C2 = " + c2); // this is a simple assignment operator Complex c3 = c2; } }
Output:
The above program has a ‘Complex’ class that has a parameterized constructor and a copy constructor. In the main method first, we create an object c1 using a parameterized constructor. Then using the below statement,
Complex c2 = new Complex (c1);
The above statement calls the copy constructor as the reference c1 is passed to the constructor while creating a new object c2.
Constructor Chaining In Java
Constructor chaining is a process of one constructor calling another constructor of the same class.
Even when we have inherited from a base class, the constructor of the base class is invoked first when the child class object is created. This is also an example of constructor chaining.
In Java, Constructor chaining can be achieved using two approaches:
- Within the same class: When we are calling one constructor from another constructor of the same class, then we can use using this () keyword.
- From base class: A constructor of the base class can be called by that of the derived class using the super keyword.
Why Do We Need Constructor Chaining?
When we want to perform multiple tasks in our constructor, then instead of performing each task in one constructor, we break down the tasks into multiple constructors, and then we call constructors from one another resulting in constructor chaining.
Given below are some of the rules that we need to follow while performing constructor chaining.
- Constructor chaining is done in any order and will produce the same results.
- The expression ‘this’ keyword should be the first expression in the constructor.
- We should have at least one constructor without this keyword.
When we have an inheritance in our program, we can also perform constructor chaining. In this case, the subclass will call the constructor of the base class. By doing this subclass objects’ creation begins with the initialization of the superclass members.
Now we will implement the constructor chaining in Java using the above approaches.
#1) Constructor Chaining Within The Same Class
class DemoClass { // No args constructor DemoClass() { System.out.println("DemoClass::No args constructor"); } // parameterized constructor DemoClass(int val1) { // calls default constructor this(); System.out.println("DemoClass::Constructor with 1 argument: " + val1); } // parameterized constructor DemoClass(int val1, int val2) { // invokes parameterized constructor with 1 argument this(5); System.out.print("DemoClass::constructor with 2 arguments:"); System.out.println("Product of 2 arguments = " + val1 * val2); } } class Main{ public static void main(String args[]) { // call parameterized constructor with 2 arguments new DemoClass(10, 15); } }
Output:
As already mentioned, we achieve constructor chaining within the same class using ‘this’ keyword. In the above program, we have three constructors and we call one constructor from another using ‘this’ keyword.
From Base Class
When a class inherits another class then the constructor of the parent class is invoked first when we create an object of a derived class which is constructor chaining.
If we want to explicitly call the base class constructor in the derived class, then we should use the keyword “super” for this purpose. Using the ‘super’ keyword we can call the superclass constructors in the inheritance hierarchy until we reach the topmost class.
The below program demonstrates the use of a ‘super’ keyword for constructor chaining.
class BaseClass { String name; // no args constructor BaseClass() { this(""); System.out.println("BaseClass::No-argument constructor"); } // Parameterized constructor BaseClass(String name) { this.name = name; System.out.println("BaseClass::Parameterized constructor"); } } class DerivedClass extends BaseClass { // No-argument constructor DerivedClass() { System.out.println("DerivedClass::No-argument constructor"); } // parameterized constructor DerivedClass(String name) { super(name); // invokes Parameterized constructor of BaseClass System.out.println("DerivedClass::Parameterized constructor"); } } class Main { public static void main(String args[]) { // invokes DerivedClass parameterized constructor DerivedClass obj = new DerivedClass("Java"); } }
Output:
In the above program, we invoke the parameterized constructor of the derived class with the value “Java”. This constructor in turn has a call to the base class constructor using “super (name);” which executes the parameterized constructor of the base class.
Frequently Asked Questions
Q #1) How do you create a Constructor in Java?
Answer: We create a constructor as a special method that has the same name as the name of the class. A constructor cannot have a return type as well. It can have access modifiers but it cannot be final, static, abstract, or synchronized.
If ABC is a class, then we can define its constructor as
ABC(){} //no args constructor OR ABC(param1, param 2, …, param n) {} //parameterized constructor
Q #2) What is the Benefit of a Constructor in Java?
Answer: Using the constructor, we can initialize the members of the class as the first thing the moment object is created. Constructor eliminates the need to call normal methods implicitly.
We can perform various tasks related to initializing, starting tasks, etc. in the constructor as constructors are invoked during the object creation phase.
Q #3) Why are Constructors used?
Answer: Constructors are mainly used to initialize the members of the class and are invoked when the object of the class is being created.
Q #4) Can Constructor be private?
Answer: Yes, we can have a private constructor. When the constructor is private, then the class can be prevented from being instantiating.
Q #5) Can Constructor be final?
Answer: No, we cannot have a final constructor.
Conclusion
In this tutorial, we have started our discussion on constructors in Java. We learned the basics of the constructor, its creation, and rules to follow. We also discussed copy constructors in Java.
The default constructor & types of constructors and concepts like constructor overloading and constructor chaining were briefed with examples. As a part of these topics, we also saw the use of ‘this’ keyword in constructors.
=> Read Through The Easy Java Training Series.