Function overloading: Difference between revisions

Content deleted Content added
Dnas (talk | contribs)
m See also: link to related topic
Line 14:
For example, a class <tt>Person<tt> that holds data about each person's name and phone number. In the example below, written in [[Java (programming language)|Java]], the constructor is ''overloaded'' as there are two constructors for the class <tt>Person<tt>.
 
<source lang="java">
<pre>
public class Person {
// instance variables:
Line 32:
}
}
</presource>
 
In Java, the call <ttcode>this.name=name</ttcode> 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 <ttcode>this(name, "N/A")</ttcode>. It must be called on the first line of the constructor and can only be called once per constructor. This is generally considered a good programming practice. It might seem more natural and clear to write the second constructor above as:
 
<source lang="java">
<pre>
public Person(String name){
this.name=name;
this.phoneNumber="N/A";
}
</presource>
 
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:
 
<source lang="java">
this.name=name;
</source>
 
in the first constructor is changed to
 
<source lang="java">
this.name=name.toLowerCase();
</source>
 
If the same line was repeated in the second constructor, then it would also need to be changed to produce the desired effect.