Google+

Like Us On Facebook


Total Pageviews

77. 'Constructor' Overloading






In addition to overloading normal methods as explained in earlier post#76, you can also overload constructor methods.

Lets implement overloading constructors concept on Eclipse IDE

1. Launch Eclipse IDE, Create a new Java Project 'Project 003', Create a Class 'Box' and Declare the instance variables 'width', 'height' and 'depth' in Box class as shown below:



  2. Create Box( ) constructor without any parameters and initialize the instance variables of Box class inside this constructor:


3. Create Box( ) constructor with all the three parameters as shown below:



4. Create Box( ) constructor with only one parameter (This is only possible when width, height and depth of the box are same) as shown below:



So we have created three constructors with same name in the Class , but with different number of parameters. Java allows to create constructors with same number but which differ in number of parameters and type of parameters.

In this example, we have created three Box( ) constructors.

5. Create volume( ) method for calculating the volume of the box using the instance variables initialized in any of the above three Box( ) constructors as shown below and save:



6. Create another class 'ArgumentsPassing', create 3 objects and call the constructors by passing the arguments in the object creation statements as shown below -



7. Call the volume( ) method of Box class to retrieve the calculated volume of the box and print them here as shown below:



8. Save and Run 'ArgumentsPassing' class as Java Application

9. Observe that the output is displayed in console as shown below:



Download this project:

Click here to download the project containing 'Box' and 'ArgumentsPassing' classes used in this post (You can download the project and import into Eclipse IDE on your machine)




Please comment below to feedback or ask questions.

How to use Objects as parameters will be explained in next post.



No comments:

Blog Index