Google
 
   
Login
Username:

Password:


Lost Password?

Register now!
Search
Main Menu
top books
Polls
What do you think about php-deluxe.net?
Excellent!
Cool
Hmm..not bad
What the hell is this?
encyclopedia
recommendation
compare webbrowser
Freenet DSL
Who's Online
4 user(s) are online (4 user(s) are browsing encyclopedia)

Members: 0
Guests: 4

more...
browser tip
recommendation!
Sponsored
partner
Germany Next Topmodel
germanys next topmodel germanys next topmodel

Constructor overloading

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 (computer science) provides a method with the same name and arguments as in a superclass (computer science).

Imagine you have a class Person that holds data about each person s name and phone number. In the (Java programming language) 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