Constructor in Java
In this class, We discuss Constructor in Java.
The reader should have prior knowledge of instance and local variables. Click Here.
Before we move on to constructors, we understand default values to instance variables.
Default Values:
1) Boolean false
2) byte 0
3) short 0
4) int 0
5) long 0L
6) char u0000
7) float 0.0f
8) double 0.0d
9) object null
Constructor: It is a block of code similar to a method. And it is called during the creation of objects.
The constructor name should be the same as the class name.
Example:
class A
{
int k;
A(int p)
{
p=k;
}
}
The above example has an instance variable and a constructor.
The constructor takes an input value of type integer.
Constructors are mostly used to initialize the instance variables.
The below example shows the constructor initialization.
The above example has a class “constructorExample.”
The class contains a constructor to initialize the instance variables.
The execution starts from the main method.
The first line in the main method is creating an object for the class “ConstructorExample.”
When we define an object, the constructor is called.
The constructor assigns 1 and 5.5 values to the instance variables p and q.
The object ob is assigned space in the heap.
The next line of code creates another object, ob1.
Creating an object constructor is called and assigns 2 and 6.5 to variables p and q.
The object ob1 is assigned a new space in the heap.
The line ob.add() will take p and q values 1 and 5.5.
The line ob1.add() will take p and q values 2 and 6.5.
The constructor assigns values to instance variables, as mentioned above.
Default Constructor:
class A
{
int p;
void add(int k)
{
code
}
}The above example does not have a constructor.
Java will automatically assign a default constructor.
The default constructor is called during the object creation.
Difference between constructor and method:
1) constructor does not have a return type.
2) Constructors can not be static, abstract, final, or synchronized.