Example 5
Suppose that a Student class has fields for a name, student number, and
number of credits. Normally, a new student will not have any credits. The
constructor for such a student might take the form
Student (String n, String sn)
{
name = n;
studentNumber = sn;
credits = 0;
}
Sometimes a new student will already have some credits from another
school. To handle such cases, we could write another constructor.
Student (String n, String sn, int c)
{
name = n;
studentNumber = sn;
credits = c;
}
Notice that the two constructors have two lines of code that are identical.
It is usually a good idea to avoid such repetition of multiple lines of code
because, if a mistake is found or if the program is being modified at a later
time, then the code must be changed in more than one place. We can avoid
such repetition here by rewriting the first constructor as follows.
Student (String n, String sn)
{
this(n,sn,O);
}
|