// Person.java // Person class declaration creates a person object // This version of Person violates its encapsulation by returning the classes array. Since objects are really // pointers, this gives the user a pointer to an internal data structure! import java.text.DecimalFormat; public class Person extends Object { private String First; // first name private String Last; // last name private int age; // age private int lastClass; // age private int classes[]; // classes taking // Person constructor initializes each instance variable to zero or empty; // ensures that each Time1 object starts in a consistent state public Person() { int temp[] = {0}; classes = new int[20]; setPerson( "George", "Smith", 20, temp ); } // set a new Person value // validity checks on the age; set invalid values to 20 public void setPerson( String First, String Last, int age, int classes[] ) { int i; this.First = First; this.Last = Last; this.age = ( ( age >= 0 && age < 100 ) ? age : 20 ); for (i = 0; i < classes.length; i++) { this.classes[i] = classes[i]; } lastClass = i - 1; } // get first name public String getFirst() { return First; } // get last name public String getLast() { return Last; } public int getAge() { return age; } // This method will break encapsulation! classes is really a pointer, so the user can directly access // an internal array! public int[] getClasses() { return classes; } public void setFirst(String First) { this.First = First; } public void setLast(String Last) { this.Last = Last; } public void setAge(int age) { this.age = age; } public void addClass(int newClass) { if (lastClass == classes.length - 1) return; else if (classes[lastClass] == 0) classes[lastClass] = newClass; else classes[++lastClass] = newClass; } public int getNumClasses() { return lastClass + 1; } public int getClass(int theElement) { return classes[theElement]; } } // end class Person /************************************************************************** * (C) Copyright 1992-2003 by Deitel & Associates, Inc. and * * Prentice Hall. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/