Constructor in Java
A constructor in java is a special method that initializes an object. In other words, a constructor in java is a block of code within a class that allows constructing the object of the class at runtime.
It is similar to a method that is invoked when an instance of a class is created using the new operator. A constructor can also accept arguments like method and can be overloaded.
The purpose of the constructor is to initialize the objects of the class. If we try to create an object of the class without specifying any constructor, JVM will create a constructor for us.
Key points of Constructor:
1. Constructor name must be the same as its name of the class in which it is declared and defined.
2. The constructor should not have any return type even void also because if there is return type then JVM would consider as a method, not a constructor. Compiler and JVM differentiate constructor and method definitions on the basis of the return type.
Suppose you define the method and constructor with the same name as that of the class name then JVM would differentiate between them by using return type.
3. Whenever you create an object/instance of a class, the constructor will be automatically called by the JVM. If you don’t define any constructor inside the class, the compiler automatically creates a default constructor at compile-time and assigns default values for all variables declared in the class.
The default values for variables are as follows:
a. Numeric variables are set to 0.
b. Strings are set to null.
c. Boolean variables are set to false.
Declaration of Constructor in Java
A java constructor can be declared inside the class by the following syntax. They are as follows:
Access modifiers_name class_name(Parameter_list)
// Constructor body which is a block of statements where you can initialize the values of instance variables, local variables, call the methods, and print output.
public Rectangle(int l, int b)
length = l; // l is a local variable.
breadth = b; // b is a local variable.
Here, Rectangle is a class name that must be the same as the name of the class that contains the constructor.
public is an access modifier that indicates that other classes can access the constructor. A constructor can be declared (optionally) as public, protected, and private. These are called access modifiers in java.
Non-access modifiers cannot be applied with constructors. By mistake, if you apply any other modifiers with constructor except these four access modifiers, you will get a compile-time error.
If you apply a private access modifier with a java constructor, you cannot create an object of that class in other classes. If somebody asks that I want to create a class but nobody should instantiate it, you can say constructor must be private.
What is Use of Constructor in Java
The use of constructor in Java is as follows:
1. The constructor is used in java programming to assign the default value of instance variables.
2. Constructor is used to initializing objects of a class and allocate appropriate memory to objects. That is, It is used to initialize the instance variables of a class with a different set of values but it is not necessary to initialize.
3. If you need to execute some code at the time of object creation, you can write them inside the constructor. Generally, it is used for the initialization of instance variables.
Use of Private Constructor in Java
How to call Constructor in Java
In Java, we can call a constructor in the following ways.
1. A a = new A(); // Here, A is name of class.
2. new A();
When we create an object of the class by using the new keyword, a constructor is automatically called. After creating the object of the class, we cannot call the constructor again.
The syntax for object creation is as follows:
Consider the following example.
School sc = new School();
School ➝ Name of the class.
sc ➝ Object reference variable which stores the address of the object in the stack memory.
School() ➝ Constructor of the class.
new ➝ It is a special keyword that allocates the memory to store the object whose type is specified by a constructor and then calls the constructor to initialize the object, which is stored in the heap( a region of memory for storing objects).
When the constructor ends, a new keyword returns memory addresses to the object so that it can be accessed from anywhere in the application.
Types of Constructors in Java
Basically, there are two types of constructors in java. They are:
1. Default Constructor (No-argument constructor)
2. Parameterized Constructor (Argument constructor)
Default Constructor in Java with Example
A constructor which has no parameter is known as default constructor in Java. When a class does not declare a constructor, JVM automatically creates a constructor for that class. This constructor is called default constructor.
We cannot pass any argument to the default constructor. That’s why it is known as a no-argument constructor. It does not do anything but it allows to create the instance of the class.
Let’s take an example program where we will do not create any constructor in the class. But Java compiler will automatically put a default constructor in the class.
Program source code 1: Suppose we have a class ‘Person’. A person has three major properties like name, age, and address, where the name, age, and address are instance variables declared inside the class.
In the preceding example program, we did not create any constructor. So, the java compiler provides a default constructor. null, 0, null is the default values of the instance variables provided by the default constructor.
Now, we can use the default constructor to initialize values of instance variables. Let’s see an example program based on it.
Program source code 2:
Let us see the memory detail behind the constructor. The below figure will show how to initialize the values of the variables inside the memory location.
We know that p is an object reference variable which contains the address of the memory location of the object. Here, 5575 is the address on the stack where we can find other detail of the class like name, age, and address on this address.
👉 A reference variable never contains an object directly. It contains an address that points to data stored in the memory location.
In the above image, you can see that when we did not initialize the values of the instance variable in the constructor in program 1, default values for variables have been stored on the heap after calling constructor.
But, when we initialized the values of variables in the constructor in program 2, After calling the constructor, default values are eliminated from the memory location and initialized values are stored in the memory location of heap.
Parameterized Constructor in Java
A constructor that takes parameters is known as parameterized constructor in java or argument constructor. The parameterized constructor is used to provide different values to the distinct object.
To call the parameterized constructor, we pass arguments while creating the object. The argument can be of any type like integer, array, character or an object. It can take any number of arguments. Java does not provide a parameterized constructor by default.
👉 We cannot define two constructors with the same number of parameters and the same types.
School sc = new School(“RSVM”, 20, “Dhanbad”); // Calling three argument constructor.
Let’s create a program where we will define default, one parameter, and two parameters constructors and call them with passing arguments.
Program source code 3:
When JVM will execute the statement Demo d = new Demo(); it will default constructor for the class. In the next line, JVM will call one argument constructor while execution of new demo(20).
The next line new Demo(10,15) will call two arguments constructor. You can see in all the three lines in the main, the same object reference variable has been used. We can also write above three lines of code in this manner:
Demo d = new Demo();
Demo d1 = new Demo(20);
Demo d2 = new Demo(10,15);
Program source code 4: In this example program, we will see the declaration of parameterized constructor in two manners. Let’s see in the below program.
Constructor with Array of Objects
Program source code 5:
Difference between Constructor & Method in Java
Constructor vs Method
|1.||Constructor is a special type of method that is used to initialize the state of an object.||Method is used to expose the behaviour of an object.|
|2.||It has no return type even void also.||It has both void and return type.|
|3.||If we don’t provide any constructor in the class, Java Compiler provides a default constructor for that class.||Method is not provided by the compiler in any case.|
|4.||Constructor name must be same as name of the class.||Method name may or may not be the same name as the class name.|
|5.||The purpose of a constructor is to create an object of a class.||The purpose of a method is to execute the functionality of the application.|
|6.||They are not inherited by subclasses.||They are inherited by subclasses.|
Key points about Java Constructor
1. When you create an object, its constructor is called before any methods.
2. If you declare your own constructor, you have to decide what values should be given to the instance variables.
3. this and super keyword must be the first line in the constructor.
4. Constructor overloading is possible but overriding is not possible.
5. It cannot be inherited in the subclasses.
6. A constructor can also call another constructor of the same class using ‘this’ and for argument constructor use ‘this(para_list).
7. A Constructor is not a keyword in Java.
Recommended post on Constructor
Hope that this tutorial has covered almost all important topics related to the Constructor in Java with example program. I hope that you will have understood default and parameterized constructors.
Thanks for reading!!!