Monday, 11 November 2013

Constructor overloading in Java

The task is to create a class called UselessClass which holds two variables int x and double y. If a class is initialized with a passed value, then it must be set in these variable while creating an instance. Else it sets the variables to zero.

The example code in Java7 is given below:




Note that UselessClass(2,4.567) and UselessClaass() are different constructors even though they have the same name. This is the concept of constructor-overloading.

While creating obj1 the first constructor over-loaded the second constructor.
While creating obj2 the second constructor over-loaded the first constructor.

The thumb-rule for using constructor over loading -

  • Name of constructors must be same as the name of the class
  • The parameters of constructors must be different else they become redundant.


| Advertisement |

No comments:

Post a Comment