// Student.java - A demo of using optional constructor arguments by // using overloaded constructors. Student objects represent students // enrolled in a college course and have many attributes not shown. // This is sometimes called the "telescoping constructor pattern". // (Validity checking of arguments and other details omitted for clarity.) // // Written 4/2007 by Wayne Pollock, Tampa Florida USA. class Student { private static int nextStudentID; static { // Typically fetched from a DB at application (JVM) startup: // ... nextStudentID = ...; } // Add a shutdown hook to save the current value of nextStudentID // to the DB when the application (the JVM) exits: // ... private int studentID; private String lastName; private String firstName; private String address; private String homePhone; private int level; // 1 = freshman, ... private Date enrolled; private char gender; // 'M' or 'F', 'U' = unknown // ... public Student ( String lastName ) { this( lastName, "" ); } public Student (String lastName, String firstName ) { this( lastName, firstName, "Unknown", "", 1, new Date(), 'U' ); } public Student (String lastName, String firstName, String address ) { this( lastName, firstName, address, "", 1, new Date(), 'U' ); } public Student (String lastName, String firstName, int level ) { this( lastName, firstName, "Unknown", "", level, new Date(), 'U' ); } ////////////////////////////////////////////////////////////////////// // Repeat for all allowed combinations of optional arguments! Note // // not all combinations are possible (e.g., last, first, phone). // // (How many constructors will there be?) // ////////////////////////////////////////////////////////////////////// // The main constructor invoked by all the others: public Student (String lastName, String firstName, String address, String homePhone, int level, Date enrolled, char gender ) { this.studentID = nextStudentID; ++nextStudentID; this.lastName = lastName; this.firstName = firstName; this.address = address; this.homePhone = homePhone; this.level = level; this.enrolled = enrolled; this.gender = gender; } // public Student methods go here: // ... } // Sample use (good luck figuring out which combinations and the // order of arguments to use): class StudentTest { Student s1 = new Student( "Doe" ); Student s2 = new Student( "Piffl", "Hymie", 'M' ); // ... }