Constructor overloading
From Wikipedia, the free encyclopedia
Constructor overloading is a technique used in object-oriented programming to allow multiple ways of creating an object using constructors with different parameter types and numbers of parameters. This is similar to method overloading, which is when methods have the same name, but take different arguments.
For example, a class Person that holds data about each person's name and phone number. In the example below, written in Java, the constructor is overloaded as there are two constructors for the class Person.
public class Person { // instance variables: String name; String phoneNumber; // Constructor with name and number: public Person(String name, String phoneNumber){ this.name=name; this.phoneNumber=phoneNumber; } // Alternative constructor without giving phone number. // This will set the phone number to "N/A" (for "not available") public Person(String name){ this(name, "N/A"); } }
In Java, the call this.name=name means "set this object's variable called name to the value of the argument name.
Note that the second constructor invokes the first one with the call this(name, "N/A"). This is generally considered a good programming practice. It might seem more natural and clear to write the second constructor above as:
public Person(String name){ this.name=name; this.phoneNumber="N/A"; }
This would work the same way as the first example. The benefit of calling one constructor from another is that it provides code that is more flexible. Suppose that the names needed to be stored in lower case only. Then only one line would need to be changed:
this.name=name;
in the first constructor is changed to
this.name=name.toLowerCase();
If the same line was repeated in the second constructor, then it would also need to be changed to produce the desired effect.