Java – Constructor overloading

Home/Java - Tutorial/Java - Classes and Methods/Java – Constructor overloading
Java – Constructor overloading 2017-08-09T10:48:21+00:00

Constructor overloading in java:

Along with method overloading, we can also overload constructors. Constructors having the same name with different parameter list is called constructor overloading.

EX :



 


Output :
–Center at 5 and 5
Radius = 3
–Center at 10 and 20
Radius = 5
–Center at 15 and 25
Radius = 10
Above program is quite complicated here i am giving you perfect flow of program.
First of all note one thing that new ClassName() this is a short  syntax of creating object of any class.
And we all know that when we create object the constructor of that class will be called automatically.
So in our program first of all due to syntax Circle c1 = new Circle(); non parameterize constructor will be called for object c1 so we get output like Center at 5 and 5 Radius = 3 in c1.display().
Next due to syntax Circle c2 = new Circle(10,20,5); constructor which has 3 arguments will be called for object c2 so we get output like Center at 10 and 20 Radius = 5 in c2.display().
Now when we define object c3 our syntax is like Circle c3 = new Circle(new Point(15,25),10); so first of all it will create object for Point class so constructor of point class will be called and it will set parameter x and y.
Then constructor of circle class which has Point class object as an argument along with one int argument will be called and set all parameter as per program and we get output like Center at 15 and 25 Radius = 10 in c3.display().
We can also write
Point p1 = new Point(15,25);
Circle c3 = new Circle(p1,10);
This is how we can pass object as an argument in constructor.
We have already seen Call by reference in which we pass object as a method argument.

Now in next topic we will discuss about how you can return an object.

Prev Next