Section 11.3. Overloading Constructors


[Page 356 (continued)]

11.3. Overloading Constructors

We can overload constructors, just as we overloaded methods. The parameter lists must be different. This can mean that they take a different number of parameters and/or that the types are different. In the above code we have two constructors. One takes no parameters, and one takes a String object, which is the name to use.

Here we have added another constructor that takes the name and an array of grades.

Program 99. Student Class with Three Constructors

public class Student {   //////////// fields //////////////////   private String name;   private double[] gradeArray;   //////////// constructors ///////////   public Student() {}   public Student(String theName)   {     this.name = theName;   }   public Student(String theName, double[] theGradeArray)   {     this.name = theName;     this.gradeArray = theGradeArray;   }   /////////// methods ///////////////   public String toString()   {     return "Student object named: " + this.name;   } }


To use this constructor we need to pass in a name as a String object and an array of grades of the type double.



Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
ISBN: N/A
EAN: N/A
Year: 2007
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net