/** *

* A Person is an object that holds personal information, * in particular, their name and phone number. *

* This is just a simple example of a Java class. *

 * Example usage: 
 *   jim = new Person('Jim Mahoney', '000-1234');
 *   jims_phone = jim.getPhone();
 *   jims_name  = jim.getName();
 *   total_number_of_people = Person.getNumberOfPeople();
 * 
* * @version 1.0, Feb 7 2007 * @author Jim Mahoney */ public class Person { // Note that by using constants for these things // rather than just embedding these strings in the code, // it's easier to see what they are and to change 'em if need be. // Note also the convention of capitalizing constants. private static final String DEFAULT_NAME = "anonymous"; private static final String DEFAULT_PHONE = "phone?"; // instance variables: there's one of these for each created object, // and you should access them with the "this" keyword. private String name; private String phone; // Running count of how many Person objects have been created. // Note that the 'static' keyword here means there is only one // of these for the whole class, not one for each instance. private static int numberOfPeople = 0; // These sort of routines are called "getters" and "setters" in Java land. public String getName(){ return this.name; } public void setName(String name){ this.name = name; } public String getPhone(){ return this.phone; } public void setPhone(String phone){ this.phone = phone; } // Note the 'static' keyword here : that means // that it is is invoked on the whole class, not an instance. private static void incrementNumberOfPeople(){ Person.numberOfPeople++; } public static int getNumberOfPeople(){ return Person.numberOfPeople; } // Constructor methods. // Note that I've put in several versions here, // depending on how you want to call it. public Person(){ this.setName(DEFAULT_NAME); this.setPhone(DEFAULT_PHONE); Person.incrementNumberOfPeople(); } public Person(String name){ this.setName(name); this.setPhone(DEFAULT_PHONE); Person.incrementNumberOfPeople(); } public Person(String name, String number){ this.setName(name); this.setPhone(number); Person.incrementNumberOfPeople(); } // Override the default Object.toString() method // that determines what this thing looks like when printed. public String toString(){ return this.getName() + " (" + this.getPhone() + ")"; } }