Parameter Constructor and overloading

What is parameter constructor?

– In java program, when we set same class name and method name that is called constructor structure in java program and when we set parameter as constructor method it’s called parameter constructor.

– Constructor method does not have return type.

– 3 types of constructor available in java program.

– 1) Default constructor, 2) parameter constructor, 3) copy constructor

 

In this blog we are working on parameter constructor programs with constructor overloading. Constructor overloading is same as method overloading in java program. constructor methods have same name but parameter different.

 

 

Let’s see example on parameter constructor with constructor overloading.

class Area

{

double areaAns = 0;

Area(int l)

{

areaAns = l*l;    // Find the area of Square

}

Area(double r)             //          Parameter Constructor

{

areaAns = 3.14 * r * r;  // Find the area of Circle

}

Area(int l,int h)

{

areaAns = l*h;  // Find the area of Rect

}

void display()

{

System.out.println(“Area : ” + areaAns);

}

}

class clEx10

{

public static void main(String args[])

{

// new Area(10);           // using of this we can not call display() method

 

Area a1 = new Area(10.5);       // call to Circle Area

a1.display();

 

// Overload the constructor

Area a2 = new Area(10,20);     // Call to Rect aRea

a2.display();

 

Area a3 = new Area(7);            // call to Square Area

a3.display();

}

}

 

Output:

Area : 346.185

Area : 200

Area : 49.0

 

This program has two concepts, one is parameter constructor and other is constructor overloading.

Here Area(int), Area(double) and Area(int,int) are three constructor in one class with same name and different parameter so we can also called constructor overloading.

 

Video available on YouTube.


[sbscrbr_form]

If you have query about this blog, you can directly post comment or subscribe on website.


Earn Money Online

1235total visits,1visits today


mayank

Hello, I am Maddy a Java blogger, trainer and developer

Related articles

Comments are closed.