Introduction:
Constructor is a special method presents under a class responsible for initializing the variable of that class.
Few points about constructor:
• The name of a constructor method is exactly the same name of the class in which it was present
• Constructor never return any value so we don’t have to define a return type for it.
• Generally, two type of constructors are there implicit constructor and explicit constructor.
• Implicit constructor: It is defined by the complier if the programmer fails to define it. It is a parameter less constructor.
• Explicit constructor: It is defined by the programmer. It can be parameter less or parameterized.
• We call constructor by creating an instance in our main method.
Types of Constructors:
1. Default or parameter less Constructor.
2. Parameterized Constructor.
3. Copy Constructor.
4. Static Constructor
Default / parameter less Constructor: If a constructor method doesn’t take any parameters then we call that as default or parameter less.
Parameterized Constructor: If a constructor method takes any parameter then it is called a parameterized constructor. These constructors can be defined by the programmers only but never can be define by implicitly.
Copy Constructor: If we want to create multiple instances with the same values then we use these copy constructors, in a copy constructor the constructor takes the same class as a parameter to it.
Static Constructor: If a constructor is explicitly declared by using static modifier, we call that as Static Constructor. All the constructor we have define till now are non-static. Static constructors are implicitly call no explicit call is required.
Practical Examples:
Implicit constructor:
Here we can see that constructor was not created by programmer it is created by compiler.
Explicit Constructor:
Copy Constructor/parameterize Constructor:
Static Constructor: