// File: TestPoly3.java // // Author: Rahul Simha // Created: Sept 16, 1998 // Modified: Sept, 2008 // // Illustrates what can go wrong when down-casting. class Customer extends Person { // New data. int loyalty; // Number of years as customer. // New constructor. public Customer (String nameIn, String ssnIn, int loyaltyIn) { // This is like calling Person (nameIn, ssnIn). super (nameIn, ssnIn); // Subclass data. loyalty = loyaltyIn; } // Override toString() public String toString () { return "Customer: name=" + name + ", " + loyalty + " years with the company"; } // Accessor: public int getLoyalty () { return loyalty; } } // End of class "Customer" // Testing. public class TestPoly3 { public static void main (String[] argv) { Customer c = new Customer ("Gullible Gus", "555-55-5678", 5); Person p = new Person ("Zany Zoe", "112-12-1212"); // This is OK because p2 is really a Customer: Person p2 = c; Customer c2 = (Customer) p2; // This will generate a run-time exception // because p is not a Customer: Customer c3 = (Customer) p; } } // End of class "TestPoly3"