Constructor Invocation:
A constructor is invoked (called) automatically whenever an object is created using the new keyword. For example, in the above example, new TicTacToe() calls the constructor of TicTacToe class. If no constructor has been defined, Java automatically invokes the default constructor which initializes all the fields to their default values.
Types of Constructor:
Based on the number of parameters and type of parameters, constructors are of three types:
- Parameter less constructor or zero parameter constructor
- Parameterized constructor
- Copy constructor
Parameter less constructor: As the name implies a zero parameter constructor or parameter less constructor doesn’t have any parameters in its signature. These are the most frequently found constructors in a Java program. Let’s consider an example for zero parameter constructor:
1
2
3
4
5
6
7
8
|
class Square
{
int side;
Square()
{
side = 4;
}
}
|
In the above example, Sqaure() is a zero parameter or parameter less constructor which initializes the side of a square to 4.
Parameterized constructor: This type of constructor contains one or more parameters in its signature. The parameters receive their values when the constructor is called. Let’s consider an example for parameterized constructor:
1
2
3
4
5
6
7
8
|
class Sqaure
{
int side;
Square(int s)
{
side = s;
}
}
|
In the above example, the Square() constructor accepts a single parameter s, which is used to initialize the side of a square.
Copy constructor: A copy constructor contains atleast one parameter of reference type. This type of constructor is generally used to create copies of the existing objects. Let’s consider an example for copy constructor:
1
2
3
4
5
6
7
8
9
10
11
12
|
class Sqaure
{
int side;
Square()
{
side = 4;
}
Square(Square original) //This is a copy constructor
{
side = original.side;
}
}
|
Now let’s an example which covers all three types of constructors:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
class Square
{
int side;
Square()
{
side = 4;
}
Square(int s)
{
side = s;
}
Square(Square original)
{
side = original.side;
}
}
The driver program is shown below:
class SquareDemo
{
public static void main(String[] args)
{
Sqaure normal = new Sqaure(); //Invokes zero parameter constructor
Square original = new Sqaure(8); //Invokes single parameter constructor
Sqaure duplicate = new Square(original); //Invokes copy constructor
System.out.println(“Side of normal square is: “+normal.side);
System.out.println(“Side of original square is: “+original.side);
System.out.println(“Side of duplicate square is: “+duplicate.side);
}
}
|
Run the above program and observe the output.
EmoticonEmoticon