Jump to content

Constructor overloading

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Quagmire (talk | contribs) at 23:39, 30 March 2004. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

In object-oriented programming it is common to use constructor overloading to allow multiple ways of creating an object.

Remember, method overloading is when methods have the same name, but take different arguments. Method overriding is when a subclass provides a method with the same name and arguments as in a superclass.

Imagine you have a class Person that holds data about each person's name and phone number. In the (Java) example below the constructor is overloaded as there are two methods with the same name ("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 a highly recommended programming practise. It might seem more natural, and clearer, to write the second constructor above as:

public Person(String name){
    this.name=name;
    this.phoneNumber="N/A";
}


Which, in this case, will work fine and have just the same effect.

So, why should you bother calling the first constructor from the second?

Because it gives you more flexible code. Suppose, for some odd reason, that you want to store the names in lower case only. Then you only need to change one line: the line

this.name=name;

in the first constructor is changed to

this.name=name.toLowerCase();

If you have the same line duplicated in the second constructor, you will have to change that as well.

See also

factory method pattern