Content deleted Content added
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">
public class Person {
// instance variables:
Line 32:
}
}
</
In Java, the call <
Note that the second constructor invokes the first one with the call <
<source lang="java">
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:
<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.
|