What is constructor?
A constructor is a special type of method of a class that initializes the object of that type. It is an instance method that usually has the same name as the class.
Important points about constructors:
- It has no return type.
- It is called through the new keyword.
- A constructor has the same name as the class.
- Generally public or default.
For example:
Types of constructor
There are basically two types of constructor as given below:
- Default constructor
- Parameterized constructor
1. Default Constructor
A "default constructor" refers to a null constructor that is automatically generated by the compiler if no constructors have been defined for the class.
A programmer-defined constructor that takes no parameters is also called a default constructor.
For example:
- class mp
{
- mp()
{
- System.out.println(“znl”);
- }
- }
2. Parameterized Constructor
It is a type of constructor that requires the passing of parameters on creation of the object.
For example:
- class mp
{
- mp(int x)
{
- System.out.println(“xml”);
- }
- }
Constructor Overloading
In Java, a constructor can also be overloaded as a feature of object oriented programming.
Whenever multiple constructors are needed, they are implemented as overloaded methods. It allows more than one constructor inside the class with a different signature.
- class mp
{
- mp()
{
- System.out.println("yahoo");
- }
- mp(int a)
{
- System.out.println("you have just selected constructor with integer value: "+a);
- }
- mp(float a)
{
- System.out.println("you have just selected constructor with float value: "+a);
- }
- mp(int a, int b)
{
- System.out.println("you have just selected constructor with integer values: "+a+" and "+b);
- }
- mp(int a, float b)
{
- System.out.println("you have just selected constructor with integer value: "+a+" and float value: "+b);
- }
- }
- class sp
{
- public static void main(String []ab)
{
- mp a1=new mp();
- new mp(3);
- new mp(3,2);
- new mp(3.3f);
- new mp(4,8.9f);
- }
- }
Output