// // simple partial example of reasonable object-oriented design // for an "address book" program, showing defining multiple classes // in a single source file. // import java.util.Hashtable ; public class AddrBook { // an instance of this class represents an address book -- // a collection of records, each of which represents // a combination of person's name, address, and phone // number. // we implement this using the Hashtable class. we use // the person's name as the key and define a class // AddrBookEntry (below) to hold the remaining data // (address and phone number). we can then retrieve // an entry by using the name as the key again. // other implementation choices are possible, for example // one based on the Vector class. Hashtable book = new Hashtable() ; void add(String name, String addr, String phone) { book.put(name, new AddrBookEntry(name, addr, phone)) ; } AddrBookEntry lookup(String name) { return (AddrBookEntry) book.get(name) ; } public static void main(String[] args) { AddrBook myBook = new AddrBook() ; myBook.add("Me", "1234 Any Street, Sometown, FL", "(800) 555-1212") ; myBook.add("You", "12 Another Road, Sometown, FL", "(888) 555-1212") ; AddrBookEntry e ; e = myBook.lookup("Me") ; System.out.println("Record for Me: ") ; System.out.println("name = " + e.name) ; System.out.println("address = " + e.address) ; System.out.println("phone = " + e.phone) ; e = myBook.lookup("You") ; System.out.println("Record for You: ") ; System.out.println("name = " + e.name) ; System.out.println("address = " + e.address) ; System.out.println("phone = " + e.phone) ; } } // second class definition -- only one public class per file allowed, // but additional non-public classes okay class AddrBookEntry { // an instance of this class represents an address book // entry (name, address, and phone number). name // is redundant if we use this class with the above // implementation of AddrBook (because it's the same // as the key used to store and retrieve records), // but could be useful if we changed AddrBook to // use, say, a vector instead. // note that we have access in AddrBook to the non-private // fields and methods of this class. they need not be // public. String name ; String address ; String phone ; AddrBookEntry(String name, String address, String phone) { this.name = name ; this.address = address ; this.phone = phone ; } }