// File: TestPoly.java // // Author: Rahul Simha // Created: Sept 16, 1998 // Modified: Sept, 2008 // // Illustrates polymorphism class Customer extends Person { // New data. int loyalty; // Number of years as customer. // New constructor. public Customer (String nameIn, String ssnIn, int loyaltyIn) { name = nameIn; ssn = ssnIn; loyalty = loyaltyIn; } // Override toString() public String toString () { return "Customer: name=" + name + ", " + loyalty + " years with the company"; } // A new method. public double discountRate () { if ( (loyalty >= 1) && (loyalty < 5) ) return 0.95; // 5% discount. else if ( (loyalty >= 5) && (loyalty < 10) ) return 0.75; // 25% discount. else if (loyalty >= 10) return 0.50; // 50% discount. else return 1.0; // no discount. } } // End of class "Customer" class Employee extends Person { int salary; // New constructor. public Employee (String nameIn, String ssnIn, int salaryIn) { name = nameIn; ssn = ssnIn; salary = salaryIn; } // Override the toString() method in Person. public String toString () { return "Employee: name=" + name + ", salary=" + salary; } } // End of class "Employee" // Testing. public class TestPoly { public static void main (String[] argv) { Customer c = new Customer ("John", "123-12-1234", 2); // What gets printed? Customer's toString() is called. System.out.println (c); Employee e = new Employee ("Paul", "234-23-2345", 50000); // What gets printed? Employee's toString() is called. System.out.println (e); // Declare some Person variables. Person p1, p2, p3, p4; // Person variables can hold Person instances p1 = new Person ("George", "345-45-3456"); p2 = new Person ("Ringo", "456-45-4567"); // ... as well as subclass instances. p3 = c; p4 = e; System.out.println ("\nPerson data: "); // Calls to toString in Person. System.out.println (p1); System.out.println (p2); // Call to toString in Customer. System.out.println (p3); // Call to toString in Employee. System.out.println (p4); } } // End of class "test_poly"