What is constructor invocation in Java Programming

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:
  1. Parameter less constructor or zero parameter constructor
  2. Parameterized constructor
  3. 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:
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:
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:
Now let’s an example which covers all three types of constructors:
Run the above program and observe the output.


EmoticonEmoticon