Esempio di Costruttore



Riscriviamo la classe Student aggiungendo il costruttore:

public class Student {

   public String name;  // Student's name
   public int ID;       // unique ID number
   public double test1, test2, test3;
                        // grades on three tests

   private static int nextUniqueID = 1;
                // next available unique ID number

   Student(String theName) {
           // constructor for Student objects;
           // provides a name for the Student,
           // and assigns the student a unique
           // ID number
           name = theName;
           ID = nextUniqueID;
           nextUniqueID++;
       }

   public double getAverage() {  // compute average test grade
          return (test1 + test2 + test3) / 3;
       }

}  // end of class Student



Siccome il costruttore di questa classe ha un parametro di tipo String, devo fornire una stringa quando lo chiamo cosi':
std = new Student("John Smith");
std1 = new Student("Mary Jones");



arrow1_left.gif (1097 byte)arrow1_right.gif (1095 byte)