46
10 Object- Oriented Programming: Polymorphism OBJECTIVES In this chapter you will learn: The concept of polymorphism. To use overridden methods to effect polymorphism. To distinguish between abstract and concrete classes. To declare abstract methods to create abstract classes. How polymorphism makes systems extensible and maintainable. To determine an object’s type at execution time. To declare and implement interfaces. One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them. —John Ronald Reuel Tolkien General propositions do not decide concrete cases. —Oliver Wendell Holmes A philosopher of imposing stature doesn’t think in a vacuum. Even his most abstract ideas are, to some extent, conditioned by what is or is not known in the time when he lives. —Alfred North Whitehead Why art thou cast down, O my soul? —Psalms 42:5

Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

  • Upload
    others

  • View
    14

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

10Object-OrientedProgramming:Polymorphism

O B J E C T I V E SIn this chapter you will learn:

■ The concept of polymorphism.

■ To use overridden methods to effect polymorphism.

■ To distinguish between abstract and concrete classes.

■ To declare abstract methods to create abstract classes.

■ How polymorphism makes systems extensible andmaintainable.

■ To determine an object’s type at execution time.

■ To declare and implement interfaces.

One Ring to rule them all,One Ring to find them,One Ring to bring them alland in the darkness bindthem.—John Ronald Reuel Tolkien

General propositions do not decide concrete cases.—Oliver Wendell Holmes

A philosopher of imposingstature doesn’t think in avacuum. Even his most abstract ideas are, to someextent, conditioned by what is or is not knownin the time when he lives.—Alfred North Whitehead

Why art thou cast down,O my soul?—Psalms 42:5

Page 2: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

2 Chapter 10 Object-Oriented Programming: Polymorphism

Self-Review Exercises10.1 Fill in the blanks in each of the following statements:

a) Polymorphism helps eliminate logic.ANS: switch

b) If a class contains at least one abstract method, it is a(n) class.ANS: abstractc) Classes from which objects can be instantiated are called classes.ANS: concreted) involves using a superclass reference to invoke methods on superclass and

subclass objects, enabling you to “program in the general.”ANS: Polymorphisme) Methods that are not interface methods and that do not provide implementations must

be declared using keyword .ANS: abstract

f) Casting a reference stored in a superclass variable to a subclass type is called.

ANS: downcasting

10.2 State whether each of the following statements is true or false. If false, explain why.a) It is possible to treat superclass objects and subclass objects similarly.ANS: True.b) All methods in an abstract superclass must be declared as abstract methods.ANS: False. An abstract class can include methods with implementations and abstract

methods.c) It is dangerous to try to invoke a subclass-only method through a subclass variable.ANS: False. Trying to invoke a subclass-only method with a superclass variable is danger-

ous.d) If a superclass declares an abstract method, a subclass must implement that method.ANS: False. Only a concrete subclass must implement the method.e) An object of a class that implements an interface may be thought of as an object of that

interface type.ANS: True.

Exercises 10.3 How does polymorphism enable you to program “in the general” rather than “in the spe-cific”? Discuss the key advantages of programming “in the general.”

ANS: Polymorphism enables the programmer to concentrate on the common operationsthat are applied to objects of all the classes in a hierarchy. The general processing ca-pabilities can be separated from any code that is specific to each class. Those generalportions of the code can accommodate new classes without modification. In somepolymorphic applications, only the code that creates the objects needs to be modifiedto extend the system with new classes.

10.4 A subclass can inherit “interface” or “implementation” from a superclass. How do inherit-ance hierarchies designed for inheriting interface differ from those designed for inheriting imple-mentation?

ANS: Hierarchies designed for implementation inheritance tend to define their functional-ity high in the hierarchy—each new subclass inherits one or more methods that weredeclared in a superclass, and the subclass uses the superclass implementations (some-times overriding the superclass methods and calling them as part of the subclass im-

Page 3: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 3

plementations). Hierarchies designed for interface inheritance tend to have theirfunctionality defined lower in the hierarchy—a superclass specifies one or more ab-stract methods that must be declared for each class in the hierarchy, and the individ-ual subclasses override these methods to provide subclass-specific implementations.

10.5 What are abstract methods? Describe the circumstances in which an abstract method wouldbe appropriate.

ANS: An abstract method is one with keyword abstract in its declaration. Abstract meth-ods do not provide implementations. Each concrete subclass of an abstract superclassmust provide concrete implementations of the superclass’s abstract methods. An ab-stract method is appropriate when it does not make sense to provide an implementa-tion for a method in a superclass (i.e., some additional subclass-specific data isrequired to implement the method in a meaningful manner).

10.6 How does polymorphism promote extensibility?ANS: Software that invokes polymorphic behavior is independent of the object types to

which messages are sent as long as those types are in the same inheritance hierarchy.New object types that can respond to existing method calls can be incorporated intoa system without requiring modification of the base system. Only client code that in-stantiates new objects must be modified to accommodate new types.

10.7 Discuss four ways in which you can assign superclass and subclass references to variables ofsuperclass and subclass types.

ANS: 1) Assigning a superclass reference to a superclass variable. 2) Assigning a subclass ref-erence to a subclass variable. 3) Assigning a subclass object’s reference to a superclassvariable is safe, because the subclass object is an object of its superclass. However, thisreference can be used to refer only to superclass members. If this code refers to sub-class-only members through the superclass variable, the compiler reports errors.4) Attempting to assign a superclass object’s reference to a subclass variable is a com-pilation error. To avoid this error, the superclass reference must be downcast to a sub-class type explicitly. At execution time, if the object to which the reference refers isnot a subclass object, an exception will occur. The instanceof operator can be usedto ensure that such a cast is performed only if the object is a subclass object.

10.8 Compare and contrast abstract classes and interfaces. When would you use an abstract class?When would you use an interface?

ANS: An abstract class describes the general notion of what it means to be an object of thatclass. Abstract classes are incomplete—they normally contain data and one or moremethods that are declared abstract because the methods cannot be implemented ina general sense. Objects of an abstract class cannot be instantiated. Subclasses mustdeclare the “missing pieces”—implementations of the abstract methods that are ap-propriate for each specific subclass. Abstract class references can refer to objects of anyof the classes below the abstract class in an inheritance hierarchy and therefore can beused to process any such objects polymorphically. An interface also describes abstractfunctionality that can be implemented by objects of any number of classes. Classesthat implement an interface can be completely unrelated, whereas concrete subclassesof the same abstract superclass are all related to one other by way of a shared super-class. An interface is often used when disparate (i.e., unrelated) classes need to providecommon functionality (i.e., methods) or use common constants. An interface canalso be used in place of an abstract class when there are no default implementationdetails (i.e., method implementations and fields) to inherit. When a class implementsan interface, it establishes an is-a relationship with the interface type, just as a subclass

Page 4: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

4 Chapter 10 Object-Oriented Programming: Polymorphism

participates in an is-a relationship with its superclass. Therefore, interface referencescan be used to evoke polymorphic behavior, just as an abstract superclass referencecan.

10.9 (Payroll System Modification) Modify the payroll system of Figs. 10.4–10.9 to include pri-

vate instance variable birthDate in class Employee. Use class Date of Fig. 8.7 to represent an em-ployee’s birthday. Add get methods to class Date and replace method toDateString with methodtoString. Assume that payroll is processed once per month. Create an array of Employee variablesto store references to the various employee objects. In a loop, calculate the payroll for each Employee

(polymorphically), and add a $100.00 bonus to the person’s payroll amount if the current monthis the one in which the Employee’s birthday occurs.

ANS:

1 // Exercise 10.9 Solution: Employee.java2 // Employee abstract superclass.34 public abstract class Employee5 {6 private String firstName;7 private String lastName;8 private String socialSecurityNumber;9 private Date birthDate;

1011 // six-argument constructor12 public Employee( String first, String last, String ssn,13 int month, int day, int year )14 {15 firstName = first;16 lastName = last;17 socialSecurityNumber = ssn;18 birthDate = new Date( month, day, year );19 } // end six-argument Employee constructor2021 // set first name22 public void setFirstName( String first )23 {24 firstName = first;25 } // end method setFirstName2627 // return first name28 public String getFirstName()29 {30 return firstName;31 } // end method getFirstName3233 // set last name34 public void setLastName( String last )35 {36 lastName = last;37 } // end method setLastName3839 // return last name40 public String getLastName()41 {

Page 5: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 5

42 return lastName;43 } // end method getLastName4445 // set social security number46 public void setSocialSecurityNumber( String ssn )47 {48 socialSecurityNumber = ssn; // should validate49 } // end method setSocialSecurityNumber5051 // return social security number52 public String getSocialSecurityNumber()53 {54 return socialSecurityNumber;55 } // end method getSocialSecurityNumber5657 // set birth date58 public void setBirthDate( int month, int day, int year )59 {60 birthDate = new Date( month, day, year );61 } // end method setBirthDate6263 // return birth date64 public Date getBirthDate()65 {66 return birthDate;67 } // end method getBirthDate6869 // return String representation of Employee object70 public String toString()71 {72 return String.format( "%s %s\n%s: %s\n%s: %s",73 getFirstName(), getLastName(),74 "social security number", getSocialSecurityNumber(),75 "birth date", getBirthDate() );76 } // end method toString7778 // abstract method overridden by subclasses79 public abstract double earnings();80 } // end abstract class Employee

1 // Exercise 10.9 Solution: Date.java2 // Date class declaration with get methods added.34 public class Date5 {6 private int month; // 1-127 private int day; // 1-31 based on month8 private int year; // any year9

10 // constructor: call checkMonth to confirm proper value for month;11 // call checkDay to confirm proper value for day12 public Date( int theMonth, int theDay, int theYear )13 {

Page 6: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

6 Chapter 10 Object-Oriented Programming: Polymorphism

14 month = checkMonth( theMonth ); // validate month15 year = theYear; // could validate year16 day = checkDay( theDay ); // validate day1718 System.out.printf(19 "Date object constructor for date %s\n", toString() );20 } // end Date constructor2122 // utility method to confirm proper month value23 private int checkMonth( int testMonth )24 {25 if ( testMonth > 0 && testMonth <= 12 ) // validate month26 return testMonth;27 else // month is invalid28 {29 System.out.printf( "Invalid month (%d) set to 1.\n", testMonth );30 return 1; // maintain object in consistent state31 } // end else32 } // end method checkMonth3334 // utility method to confirm proper day value based on month and year35 private int checkDay( int testDay )36 {37 int daysPerMonth[] =38 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };3940 // check if day in range for month41 if ( testDay > 0 && testDay <= daysPerMonth[ month ] )42 return testDay;4344 // check for leap year45 if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||46 ( year % 4 == 0 && year % 100 != 0 ) ) )47 return testDay;4849 System.out.printf( "Invalid day (%d) set to 1.\n", testDay );5051 return 1; // maintain object in consistent state52 } // end method checkDay5354 // return day55 public int getDay()56 {57 return day;58 } // end method getDay5960 // return month61 public int getMonth()62 {63 return month;64 } // end method getMonth6566 // return year67 public int getYear()

Page 7: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 7

68 {69 return year;70 } // end method getYear7172 // return a String of the form month/day/year73 public String toString()74 {75 return String.format( "%d/%d/%d", month, day, year ); 76 } // end method toString77 } // end class Date

1 // Exercise 10.9 Solution: SalariedEmployee.java2 // SalariedEmployee class derived from Employee.34 public class SalariedEmployee extends Employee5 {6 private double weeklySalary;78 // seven-argument constructor9 public SalariedEmployee( String first, String last, String ssn,

10 int month, int day, int year, double salary )11 {12 super( first, last, ssn, month, day, year ); 13 setWeeklySalary( salary );14 } // end seven-argument SalariedEmployee constructor1516 // set salary17 public void setWeeklySalary( double salary )18 {19 weeklySalary = salary < 0.0 ? 0.0 : salary;20 } // end method setWeeklySalary2122 // return salary23 public double getWeeklySalary()24 {25 return weeklySalary;26 } // end method getWeeklySalary2728 // calculate earnings; override abstract method earnings in Employee29 public double earnings()30 {31 return getWeeklySalary();32 } // end method earnings3334 // return String representation of SalariedEmployee object35 public String toString()36 {37 return String.format( "salaried employee: %s\n%s: $%,.2f",38 super.toString(), "weekly salary", getWeeklySalary() );39 } // end method toString40 } // end class SalariedEmployee

Page 8: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

8 Chapter 10 Object-Oriented Programming: Polymorphism

1 // Exercise 10.9 Solution: HourlyEmployee.java2 // HourlyEmployee class derived from Employee.34 public class HourlyEmployee extends Employee5 {6 private double wage; // wage per hour7 private double hours; // hours worked for week89 // eight-argument constructor

10 public HourlyEmployee( String first, String last, String ssn,11 int month, int day, int year,12 double hourlyWage, double hoursWorked )13 {14 super( first, last, ssn, month, day, year );15 setWage( hourlyWage );16 setHours( hoursWorked );17 } // end eight-argument HourlyEmployee constructor1819 // set wage20 public void setWage( double hourlyWage )21 {22 wage = hourlyWage < 0.0 ? 0.0 : hourlyWage;23 } // end method setWage2425 // return wage26 public double getWage()27 {28 return wage;29 } // end method getWage3031 // set hours worked32 public void setHours( double hoursWorked )33 {34 hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) ) ?35 hoursWorked : 0.0;36 } // end method setHours3738 // return hours worked39 public double getHours()40 {41 return hours;42 } // end method getHours4344 // calculate earnings; override abstract method earnings in Employee45 public double earnings()46 {47 if ( getHours() <= 40 ) // no overtime48 return getWage() * getHours();49 else50 return 40 * getWage() + ( getHours() - 40 ) * getWage() * 1.5;51 } // end method earnings5253 // return String representation of HourlyEmployee object54 public String toString()

Page 9: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 9

55 {56 return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f",57 super.toString(), "hourly wage", getWage(),58 "hours worked", getHours() );59 } // end method toString60 } // end class HourlyEmployee

1 // Exercise 10.9 Solution: CommissionEmployee.java2 // CommissionEmployee class derived from Employee.34 public class CommissionEmployee extends Employee5 {6 private double grossSales; // gross weekly sales7 private double commissionRate; // commission percentage89 // eight-argument constructor

10 public CommissionEmployee( String first, String last, String ssn,11 int month, int day, int year, double sales, double rate )12 {13 super( first, last, ssn, month, day, year );14 setGrossSales( sales );15 setCommissionRate( rate );16 } // end eight-argument CommissionEmployee constructor1718 // set commission rate19 public void setCommissionRate( double rate )20 {21 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;22 } // end method setCommissionRate2324 // return commission rate25 public double getCommissionRate()26 {27 return commissionRate;28 } // end method getCommissionRate2930 // set gross sales amount31 public void setGrossSales( double sales )32 {33 grossSales = sales < 0.0 ? 0.0 : sales;34 } // end method setGrossSales3536 // return gross sales amount37 public double getGrossSales()38 {39 return grossSales;40 } // end method getGrossSales4142 // calculate earnings; override abstract method earnings in Employee43 public double earnings()44 {45 return getCommissionRate() * getGrossSales();46 } // end method earnings

Page 10: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

10 Chapter 10 Object-Oriented Programming: Polymorphism

4748 // return String representation of CommissionEmployee object49 public String toString()50 {51 return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f",52 "commission employee", super.toString(),53 "gross sales", getGrossSales(),54 "commission rate", getCommissionRate() );55 } // end method toString56 } // end class CommissionEmployee

1 // Exercise 10.9 Solution: BasePlusCommissionEmployee.java2 // BasePlusCommissionEmployee class derived from CommissionEmployee.34 public class BasePlusCommissionEmployee extends CommissionEmployee5 {6 private double baseSalary; // base salary per week78 // nine-argument constructor9 public BasePlusCommissionEmployee( String first, String last,

10 String ssn, int month, int day, int year,11 double sales, double rate, double salary )12 {13 super( first, last, ssn, month, day, year, sales, rate );14 setBaseSalary( salary );15 } // end nine-argument BasePlusCommissionEmployee constructor1617 // set base salary18 public void setBaseSalary( double salary )19 {20 baseSalary = salary < 0.0 ? 0.0 : salary; // non-negative21 } // end method setBaseSalary2223 // return base salary24 public double getBaseSalary()25 {26 return baseSalary;27 } // end method getBaseSalary2829 // calculate earnings; override method earnings in CommissionEmployee30 public double earnings()31 {32 return getBaseSalary() + super.earnings();33 } // end method earnings3435 // return String representation of BasePlusCommissionEmployee object36 public String toString()37 {38 return String.format( "%s %s; %s: $%,.2f",39 "base-salaried", super.toString(),40 "base salary", getBaseSalary() );41 } // end method toString42 } // end class BasePlusCommissionEmployee

Page 11: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 11

1 // Exercise 10.9 Solution: PayrollSystemTest.java2 // Employee hierarchy test program.3 import java.util.Scanner; // program uses Scanner to obtain user input45 public class PayrollSystemTest 6 {7 public static void main( String args[] )8 {9 // create subclass objects

10 SalariedEmployee salariedEmployee =11 new SalariedEmployee(12 "John", "Smith", "111-11-1111", 6, 15, 1944, 800.00 );13 HourlyEmployee hourlyEmployee =14 new HourlyEmployee(15 "Karen", "Price", "222-22-2222", 12, 29, 1960, 16.75, 40 );16 CommissionEmployee commissionEmployee =17 new CommissionEmployee(18 "Sue", "Jones", "333-33-3333", 9, 8, 1954, 10000, .06 );19 BasePlusCommissionEmployee basePlusCommissionEmployee =20 new BasePlusCommissionEmployee(21 "Bob", "Lewis", "444-44-4444", 3, 2, 1965, 5000, .04, 300 );2223 System.out.println( "Employees processed individually:\n" );2425 System.out.printf( "%s\n%s: $%,.2f\n\n",26 salariedEmployee, "earned", salariedEmployee.earnings() );27 System.out.printf( "%s\n%s: $%,.2f\n\n",28 hourlyEmployee, "earned", hourlyEmployee.earnings() );29 System.out.printf( "%s\n%s: $%,.2f\n\n",30 commissionEmployee, "earned", commissionEmployee.earnings() );31 System.out.printf( "%s\n%s: $%,.2f\n\n",32 basePlusCommissionEmployee,33 "earned", basePlusCommissionEmployee.earnings() );3435 // create four-element Employee array36 Employee employees[] = new Employee[ 4 ]; 3738 // initialize array with Employees39 employees[ 0 ] = salariedEmployee;40 employees[ 1 ] = hourlyEmployee;41 employees[ 2 ] = commissionEmployee; 42 employees[ 3 ] = basePlusCommissionEmployee;4344 Scanner input = new Scanner( System.in ); // to get current month45 int currentMonth;4647 // get and validate current month48 do49 {50 System.out.print( "Enter the current month (1 - 12): " );51 currentMonth = input.nextInt();52 System.out.println();53 } while ( ( currentMonth < 1 ) || ( currentMonth > 12 ) );54

Page 12: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

12 Chapter 10 Object-Oriented Programming: Polymorphism

55 System.out.println( "Employees processed polymorphically:\n" );5657 // generically process each element in array employees58 for ( Employee currentEmployee : employees )59 {60 System.out.println( currentEmployee ); // invokes toString6162 // determine whether element is a BasePlusCommissionEmployee63 if ( currentEmployee instanceof BasePlusCommissionEmployee )64 {65 // downcast Employee reference to66 // BasePlusCommissionEmployee reference67 BasePlusCommissionEmployee employee =68 ( BasePlusCommissionEmployee ) currentEmployee;6970 double oldBaseSalary = employee.getBaseSalary();71 employee.setBaseSalary( 1.10 * oldBaseSalary );72 System.out.printf(73 "new base salary with 10%% increase is: $%,.2f\n",74 employee.getBaseSalary() );75 } // end if7677 // if month of employee's birthday, add $100 to salary78 if ( currentMonth == currentEmployee.getBirthDate().getMonth() )79 System.out.printf(80 "earned $%,.2f %s\n\n", currentEmployee.earnings(),81 "plus $100.00 birthday bonus" );82 else83 System.out.printf(84 "earned $%,.2f\n\n", currentEmployee.earnings() );85 } // end for8687 // get type name of each object in employees array88 for ( int j = 0; j < employees.length; j++ )89 System.out.printf( "Employee %d is a %s\n", j,90 employees[ j ].getClass().getName() ); 91 } // end main92 } // end class PayrollSystemTest

Page 13: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 13

Date object constructor for date 6/15/1944Date object constructor for date 12/29/1960Date object constructor for date 9/8/1954Date object constructor for date 3/2/1965Employees processed individually:

salaried employee: John Smithsocial security number: 111-11-1111birth date: 6/15/1944weekly salary: $800.00earned: $800.00

hourly employee: Karen Pricesocial security number: 222-22-2222birth date: 12/29/1960hourly wage: $16.75; hours worked: 40.00earned: $670.00

commission employee: Sue Jonessocial security number: 333-33-3333birth date: 9/8/1954gross sales: $10,000.00; commission rate: 0.06earned: $600.00

base-salaried commission employee: Bob Lewissocial security number: 444-44-4444birth date: 3/2/1965gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00earned: $500.00

Enter the current month (1 - 12): 3

Page 14: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

14 Chapter 10 Object-Oriented Programming: Polymorphism

10.10 (Shape Hierarchy) Implement the Shape hierarchy shown in Fig. 9.3. Each TwoDimension-

alShape should contain method getArea to calculate the area of the two-dimensional shape. EachThreeDimensionalShape should have methods getArea and getVolume to calculate the surface areaand volume, respectively, of the three-dimensional shape. Create a program that uses an array ofShape references to objects of each concrete class in the hierarchy. The program should print a textdescription of the object to which each array element refers. Also, in the loop that processes all theshapes in the array, determine whether each shape is a TwoDimensionalShape or a ThreeDimension-

alShape. If it is a TwoDimensionalShape, display its area. If it is a ThreeDimensionalShape, displayits area and volume.

ANS:

Employees processed polymorphically:

salaried employee: John Smithsocial security number: 111-11-1111birth date: 6/15/1944weekly salary: $800.00earned $800.00

hourly employee: Karen Pricesocial security number: 222-22-2222birth date: 12/29/1960hourly wage: $16.75; hours worked: 40.00earned $670.00

commission employee: Sue Jonessocial security number: 333-33-3333birth date: 9/8/1954gross sales: $10,000.00; commission rate: 0.06earned $600.00

base-salaried commission employee: Bob Lewissocial security number: 444-44-4444birth date: 3/2/1965gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00new base salary with 10% increase is: $330.00earned $530.00 plus $100.00 birthday bonus

Employee 0 is a SalariedEmployeeEmployee 1 is a HourlyEmployeeEmployee 2 is a CommissionEmployeeEmployee 3 is a BasePlusCommissionEmployee

1 // Exercise 10.10 Solution: Shape.java2 // Definition of class Shape.34 public abstract class Shape5 {6 private int x; // x coordinate7 private int y; // y coordinate89 // two-argument constructor

10 public Shape( int x, int y )

Page 15: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 15

11 {12 this.x = x;13 this.y = y;14 } // end two-argument Shape constructor1516 // set x coordinate17 public void setX( int x )18 {19 this.x = x;20 } // end method setX2122 // set y coordinate23 public void setY( int y )24 {25 this.y = y;26 } // end method setY2728 // get x coordinate29 public int getX()30 {31 return x;32 } // end method getX3334 // get y coordinate35 public int getY()36 {37 return y;38 } // end method getY3940 // return String representation of Shape object41 public String toString()42 {43 return String.format( "(%d, %d)", getX(), getY() );44 }4546 // abstract methods47 public abstract String getName();48 } // end class Shape

1 // Exercise 10.10 Solution: TwoDimensionalShape.java2 // Definition of class TwoDimensionalShape.34 public abstract class TwoDimensionalShape extends Shape5 {6 private int dimension1;7 private int dimension2;89 // four-argument constructor

10 public TwoDimensionalShape( int x, int y, int d1, int d2 )11 {12 super( x, y );13 dimension1 = d1;14 dimension2 = d2;

Page 16: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

16 Chapter 10 Object-Oriented Programming: Polymorphism

15 } // end four-argument TwoDimensionalShape constructor1617 // set methods18 public void setDimension1( int d )19 {20 dimension1 = d;21 } // end method setDimension12223 public void setDimension2( int d )24 {25 dimension2 = d;26 } // end method setDimension22728 // get methods29 public int getDimension1()30 {31 return dimension1;32 } // end method getDimension13334 public int getDimension2()35 {36 return dimension2;37 } // end method getDimension23839 // abstract method40 public abstract int getArea();41 } // end class TwoDimensionalShape

1 // Exercise 10.10 Solution: Circle.java2 // Definition of class Circle.34 public class Circle extends TwoDimensionalShape5 {6 // three-argument constructor7 public Circle( int x, int y, int radius )8 {9 super( x, y, radius, radius );

10 } // end three-argument Circle constructor1112 // overridden methods13 public String getName()14 {15 return "Circle";16 } // end method getName1718 public int getArea()19 {20 return ( int )21 ( Math.PI * getRadius() * getRadius() );22 } // end method getArea2324 // set method25 public void setRadius( int radius )

Page 17: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 17

26 {27 setDimension1( radius );28 setDimension2( radius );29 } // end method setRadius3031 // get method32 public int getRadius()33 {34 return getDimension1();35 } // end method getRadius3637 public String toString()38 {39 return String.format( "%s %s: %d\n",40 super.toString(), "radius", getRadius() );41 } // end method toString42 } // end class Circle

1 // Exercise 10.10 Solution: Square.java2 // Definition of class Square.34 public class Square extends TwoDimensionalShape5 {6 // three-argument constructor7 public Square( int x, int y, int side )8 {9 super( x, y, side, side );

10 } // end three-argument Square constructor1112 // overridden methods13 public String getName()14 {15 return "Square";16 } // end method getName1718 public int getArea()19 {20 return getSide() * getSide();21 } // end method getArea2223 // set method24 public void setSide( int side )25 {26 setDimension1( side );27 setDimension2( side );28 } // end method setSide2930 // get method31 public int getSide()32 {33 return getDimension1();34 } // end method getSide35

Page 18: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

18 Chapter 10 Object-Oriented Programming: Polymorphism

36 public String toString()37 {38 return String.format( "%s %s: %d\n",39 super.toString(), "side", getSide() );40 } // end method toString41 } // end class Square

1 // Exercise 10.10 Solution: ThreeDimensionalShape.java2 // Definition of class ThreeDimensionalShape.34 public abstract class ThreeDimensionalShape extends Shape5 {6 private int dimension1;7 private int dimension2;8 private int dimension3;9

10 // five-argument constructor11 public ThreeDimensionalShape(12 int x, int y, int d1, int d2, int d3 )13 {14 super( x, y );15 dimension1 = d1;16 dimension2 = d2;17 dimension3 = d3;18 } // end five-argument ThreeDimensionalShape constructor1920 // set methods21 public void setDimension1( int d )22 {23 dimension1 = d;24 } // end method setDimension12526 public void setDimension2( int d )27 {28 dimension2 = d;29 } // end method setDimension23031 public void setDimension3( int d )32 {33 dimension3 = d;34 } // end method setDimension33536 // get methods37 public int getDimension1()38 {39 return dimension1;40 } // end method getDimension14142 public int getDimension2()43 {44 return dimension2;45 } // end method getDimension246

Page 19: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 19

47 public int getDimension3()48 {49 return dimension3;50 } // end method getDimension35152 // abstract methods53 public abstract int getArea();54 public abstract int getVolume();55 } // end class ThreeDimensionalShape

1 // Exercise 10.10 Solution: Sphere.java2 // Definition of class Sphere.34 public class Sphere extends ThreeDimensionalShape5 {6 // three-argument constructor7 public Sphere( int x, int y, int radius )8 {9 super( x, y, radius, radius, radius );

10 } // end three-argument Shape constructor1112 // overridden methods13 public String getName()14 {15 return "Sphere";16 } // end method getName1718 public int getArea()19 {20 return ( int ) ( 4 * Math.PI * getRadius() * getRadius() );21 } // end method getArea2223 public int getVolume()24 {25 return ( int ) ( 4.0 / 3.0 * Math.PI *26 getRadius() * getRadius() * getRadius() );27 } // end method getVolume2829 // set method30 public void setRadius( int radius )31 {32 setDimension1( radius );33 setDimension2( radius );34 setDimension3( radius );35 } // end method setRadius3637 // get method38 public int getRadius()39 {40 return getDimension1();41 } // end method getRadius4243 public String toString()

Page 20: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

20 Chapter 10 Object-Oriented Programming: Polymorphism

44 {45 return String.format( "%s %s: %d\n",46 super.toString(), "radius", getRadius() );47 } // end method toString48 } // end class Sphere

1 // Exercise 10.10 Solution: Cube.java2 // Definition of class Cube.34 public class Cube extends ThreeDimensionalShape5 {6 // three-argument constructor7 public Cube( int x, int y, int side )8 {9 super( x, y, side, side, side );

10 } // end three-argument Cube constructor1112 // overridden methods13 public String getName()14 {15 return "Cube";16 } // end method getName1718 public int getArea()19 {20 return ( int ) ( 6 * getSide() * getSide() );21 } // end method getArea2223 public int getVolume()24 {25 return ( int ) ( getSide() * getSide() * getSide() );26 } // end method getVolume2728 // set method29 public void setSide( int side )30 {31 setDimension1( side );32 setDimension2( side );33 setDimension3( side );34 } // end method setSide3536 // get method37 public int getSide()38 {39 return getDimension1();40 } // end method getSide4142 public String toString()43 {44 return String.format( "%s %s: %d\n",45 super.toString(), "side", getSide() );46 } // end method toString47 } // end class Cube

Page 21: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 21

1 // Exercise 10.10 Solution: ShapeTest.java2 // Program tests the Shape hierarchy.34 public class ShapeTest 5 {6 // create Shape objects and display their information7 public static void main( String args[] )8 {9 Shape shapes[] = new Shape[ 4 ];

10 shapes[ 0 ] = new Circle( 22, 88, 4 );11 shapes[ 1 ] = new Square( 71, 96, 10 );12 shapes[ 2 ] = new Sphere( 8, 89, 2 );13 shapes[ 3 ] = new Cube( 79, 61, 8 );1415 // call method print on all shapes16 for ( Shape currentShape : shapes )17 {18 System.out.printf( "%s: %s",19 currentShape.getName(), currentShape );2021 if ( currentShape instanceof TwoDimensionalShape )22 {23 TwoDimensionalShape twoDimensionalShape =24 ( TwoDimensionalShape ) currentShape;2526 System.out.printf( "%s's area is %s\n",27 currentShape.getName(), twoDimensionalShape.getArea() );28 } // end if2930 if ( currentShape instanceof ThreeDimensionalShape )31 {32 ThreeDimensionalShape threeDimensionalShape =33 ( ThreeDimensionalShape ) currentShape;3435 System.out.printf( "%s's area is %s\n",36 currentShape.getName(), threeDimensionalShape.getArea() );37 System.out.printf( "%s's volume is %s\n",38 currentShape.getName(),39 threeDimensionalShape.getVolume() );40 } // end if4142 System.out.println();43 } // end for44 } // end main45 } // end class ShapeTest

Page 22: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

22 Chapter 10 Object-Oriented Programming: Polymorphism

10.11 (Payroll System Modification) Modify the payroll system of Figs. 10.4–10.9 to include an ad-ditional Employee subclass PieceWorker that represents an employee whose pay is based on the num-ber of pieces of merchandise produced. Class PieceWorker should contain private instancevariables wage (to store the employee’s wage per piece) and pieces (to store the number of piecesproduced). Provide a concrete implementation of method earnings in class PieceWorker that cal-culates the employee’s earnings by multiplying the number of pieces produced by the wage perpiece. Create an array of Employee variables to store references to objects of each concrete class inthe new Employee hierarchy. For each Employee, display its string representation and earnings.

ANS:

Circle: [22, 88] radius: 4Circle's area is 50

Square: [71, 96] side: 10Square's area is 100

Sphere: [8, 89] radius: 2Sphere's area is 50Sphere's volume is 33

Cube: [79, 61] side: 8Cube's area is 384Cube's volume is 512

1 // Exercise 10.11 Solution: PieceWorker2 // PieceWorker class extends Employee.34 public class PieceWorker extends Employee5 {6 private double wage; // wage per piece7 private int pieces; // pieces of merchandise produced in week89 // five-argument constructor

10 public PieceWorker( String first, String last, String ssn,11 double wagePerPiece, int piecesProduced )12 {13 super( first, last, ssn );14 setWage( wagePerPiece ); // validate and store wage per piece15 setPieces( piecesProduced ); // validate and store pieces produced16 } // end five-argument PieceWorker constructor1718 // set wage19 public void setWage( double wagePerPiece )20 {21 wage = ( wagePerPiece < 0.0 ) ? 0.0 : wagePerPiece;22 } // end method setWage2324 // return wage25 public double getWage()26 {27 return wage;28 } // end method getWage

Page 23: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 23

2930 // set pieces produced31 public void setPieces( int piecesProduced )32 {33 pieces = ( piecesProduced < 0 ) ? 0 : piecesProduced;34 } // end method setPieces3536 // return pieces produced37 public int getPieces()38 {39 return pieces;40 } // end method getPieces4142 // calculate earnings; override abstract method earnings in Employee43 public double earnings()44 {45 return getPieces() * getWage();46 } // end method earnings4748 // return String representation of PieceWorker object49 public String toString()50 {51 return String.format( "%s: %s\n%s: $%,.2f; %s: %d",52 "piece worker", super.toString(),53 "wage per piece", getWage(), "pieces produced", getPieces() );54 } // end method toString55 } // end class PieceWorker

1 // Exercise 10.11 Solution: PayrollSystemTest.java2 // Employee hierarchy test program.34 public class PayrollSystemTest 5 {6 public static void main( String args[] )7 {8 // create five-element Employee array9 Employee employees[] = new Employee[ 5 ];

1011 // initialize array with Employees12 employees[ 0 ] = new SalariedEmployee(13 "John", "Smith", "111-11-1111", 800.00 );14 employees[ 1 ] = new HourlyEmployee(15 "Karen", "Price", "222-22-2222", 16.75, 40 );16 employees[ 2 ] = new CommissionEmployee(17 "Sue", "Jones", "333-33-3333", 10000, .06 ); 18 employees[ 3 ] = new BasePlusCommissionEmployee(19 "Bob", "Lewis", "444-44-4444", 5000, .04, 300 );20 employees[ 4 ] = new PieceWorker(21 "Rick", "Bridges", "555-55-5555", 2.25, 400 );2223 System.out.println( "Employees processed polymorphically:\n" );2425 // generically process each element in array employees

Page 24: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

24 Chapter 10 Object-Oriented Programming: Polymorphism

10.12 (Accounts Payable System Modification) In this exercise, we modify the accounts payable ap-plication of Figs. 10.11–10.15 to include the complete functionality of the payroll application ofFigs. 10.4–10.9. The application should still process two Invoice objects, but now should processone object of each of the four Employee subclasses. If the object currently being processed is a Base-PlusCommissionEmployee, the application should increase the BasePlusCommissionEmployee’s basesalary by 10%. Finally, the application should output the payment amount for each object. Com-plete the following steps to create the new application:

a) Modify classes HourlyEmployee (Fig. 10.6) and CommissionEmployee (Fig. 10.7) toplace them in the Payable hierarchy as subclasses of the version of Employee (Fig. 10.13)that implements Payable. [Hint: Change the name of method earnings to getPayment-

Amount in each subclass so that the class satisfies its inherited contract with interfacePayable.]

ANS:

26 for ( Employee currentEmployee : employees )27 {28 System.out.println( currentEmployee ); // invokes toString29 System.out.printf(30 "earned $%,.2f\n\n", currentEmployee.earnings() );31 } // end for32 } // end main33 } // end class PayrollSystemTest

Employees processed polymorphically:

salaried employee: John Smithsocial security number: 111-11-1111weekly salary: $800.00earned $800.00

hourly employee: Karen Pricesocial security number: 222-22-2222hourly wage: $16.75; hours worked: 40.00earned $670.00

commission employee: Sue Jonessocial security number: 333-33-3333gross sales: $10,000.00; commission rate: 0.06earned $600.00

base-salaried commission employee: Bob Lewissocial security number: 444-44-4444gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00earned $500.00

piece worker: Rick Bridgessocial security number: 555-55-5555wage per piece: $2.25; pieces produced: 400earned $900.00

1 // Exercise 10.12 Solution: HourlyEmployee.java2 // HourlyEmployee class extends Employee, which implements Payable.

Page 25: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 25

34 public class HourlyEmployee extends Employee5 {6 private double wage; // wage per hour7 private double hours; // hours worked for week89 // five-argument constructor

10 public HourlyEmployee( String first, String last, String ssn,11 double hourlyWage, double hoursWorked )12 {13 super( first, last, ssn );14 setWage( hourlyWage ); // validate and store hourly wage15 setHours( hoursWorked ); // validate and store hours worked16 } // end five-argument HourlyEmployee constructor1718 // set wage19 public void setWage( double hourlyWage )20 {21 wage = ( hourlyWage < 0.0 ) ? 0.0 : hourlyWage;22 } // end method setWage2324 // return wage25 public double getWage()26 {27 return wage;28 } // end method getWage2930 // set hours worked31 public void setHours( double hoursWorked )32 {33 hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) ) ?34 hoursWorked : 0.0;35 } // end method setHours3637 // return hours worked38 public double getHours()39 {40 return hours;41 } // end method getHours4243 // calculate earnings; implement interface Payable method not44 // implemented by superclass Employee45 public double getPaymentAmount()46 {47 if ( getHours() <= 40 ) // no overtime48 return getWage() * getHours();49 else50 return 40 * getWage() + ( getHours() - 40 ) * getWage() * 1.5;51 } // end method getPaymentAmount5253 // return String representation of HourlyEmployee object54 public String toString()55 {56 return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f",

Page 26: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

26 Chapter 10 Object-Oriented Programming: Polymorphism

57 super.toString(), "hourly wage", getWage(),58 "hours worked", getHours() );59 } // end method toString60 } // end class HourlyEmployee

1 // Exercise 10.12 Solution: CommissionEmployee.java2 // CommissionEmployee class extends Employee, which implements Payable.34 public class CommissionEmployee extends Employee5 {6 private double grossSales; // gross weekly sales7 private double commissionRate; // commission percentage89 // five-argument constructor

10 public CommissionEmployee( String first, String last, String ssn,11 double sales, double rate )12 {13 super( first, last, ssn );14 setGrossSales( sales );15 setCommissionRate( rate );16 } // end five-argument CommissionEmployee constructor1718 // set commission rate19 public void setCommissionRate( double rate )20 {21 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;22 } // end method setCommissionRate2324 // return commission rate25 public double getCommissionRate()26 {27 return commissionRate;28 } // end method getCommissionRate2930 // set gross sales amount31 public void setGrossSales( double sales )32 {33 grossSales = ( sales < 0.0 ) ? 0.0 : sales;34 } // end method setGrossSales3536 // return gross sales amount37 public double getGrossSales()38 {39 return grossSales;40 } // end method getGrossSales4142 // calculate earnings; implement interface Payable method not43 // implemented by superclass Employee44 public double getPaymentAmount()45 {46 return getCommissionRate() * getGrossSales();47 } // end method getPaymentAmount48

Page 27: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 27

b) Modify class BasePlusCommissionEmployee (Fig. 10.8) such that it extends the versionof class CommissionEmployee created in Part a.

ANS:

49 // return String representation of CommissionEmployee object50 public String toString()51 {52 return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f",53 "commission employee", super.toString(),54 "gross sales", getGrossSales(),55 "commission rate", getCommissionRate() );56 } // end method toString57 } // end class CommissionEmployee

1 // Exercise 10.12 Solution: BasePlusCommissionEmployee.java2 // BasePlusCommissionEmployee class extends CommissionEmployee.34 public class BasePlusCommissionEmployee extends CommissionEmployee5 {6 private double baseSalary; // base salary per week78 // six-argument constructor9 public BasePlusCommissionEmployee( String first, String last,

10 String ssn, double sales, double rate, double salary )11 {12 super( first, last, ssn, sales, rate );13 setBaseSalary( salary ); // validate and store base salary14 } // end six-argument BasePlusCommissionEmployee constructor1516 // set base salary17 public void setBaseSalary( double salary )18 {19 baseSalary = ( salary < 0.0 ) ? 0.0 : salary; // non-negative20 } // end method setBaseSalary2122 // return base salary23 public double getBaseSalary()24 {25 return baseSalary;26 } // end method getBaseSalary2728 // calculate earnings; override CommissionEmployee implementation of29 // interface Payable method30 public double getPaymentAmount()31 {32 return getBaseSalary() + super.getPaymentAmount();33 } // end method getPaymentAmount3435 // return String representation of BasePlusCommissionEmployee object36 public String toString()37 {38 return String.format( "%s %s; %s: $%,.2f",

Page 28: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

28 Chapter 10 Object-Oriented Programming: Polymorphism

c) Modify PayableInterfaceTest (Fig. 10.15) to polymorphically process two Invoices,one SalariedEmployee, one HourlyEmployee, one CommissionEmployee and one Base-

PlusCommissionEmployee. First output a string representation of each Payable object.Next, if an object is a BasePlusCommissionEmployee, increase its base salary by 10%. Fi-nally, output the payment amount for each Payable object.

ANS:

39 "base-salaried", super.toString(),40 "base salary", getBaseSalary() );41 } // end method toString42 } // end class BasePlusCommissionEmployee

1 // Exercise 10.12 Solution: PayableInterfaceTest.java2 // Tests interface Payable.34 public class PayableInterfaceTest 5 {6 public static void main( String args[] )7 {8 // create six-element Payable array9 Payable payableObjects[] = new Payable[ 6 ];

1011 // populate array with objects that implement Payable12 payableObjects[ 0 ] = new Invoice( "01234", "seat", 2, 375.00 );13 payableObjects[ 1 ] = new Invoice( "56789", "tire", 4, 79.95 );14 payableObjects[ 2 ] =15 new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 );16 payableObjects[ 3 ] =17 new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 );18 payableObjects[ 4 ] =19 new CommissionEmployee(20 "Sue", "Jones", "333-33-3333", 10000, .06 );21 payableObjects[ 5 ] =22 new BasePlusCommissionEmployee(23 "Bob", "Lewis", "444-44-4444", 5000, .04, 300 );2425 System.out.println(26 "Invoices and Employees processed polymorphically:\n" ); 2728 // generically process each element in array payableObjects29 for ( Payable currentPayable : payableObjects )30 {31 // output currentPayable and its appropriate payment amount32 System.out.printf( "%s \n", currentPayable.toString() ); 3334 if ( currentPayable instanceof BasePlusCommissionEmployee )35 {36 // downcast Payable reference to37 // BasePlusCommissionEmployee reference38 BasePlusCommissionEmployee employee =39 ( BasePlusCommissionEmployee ) currentPayable;40

Page 29: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

Exercises 29

41 double oldBaseSalary = employee.getBaseSalary();42 employee.setBaseSalary( 1.10 * oldBaseSalary );43 System.out.printf(44 "new base salary with 10%% increase is: $%,.2f\n",45 employee.getBaseSalary() );46 } // end if4748 System.out.printf( "%s: $%,.2f\n\n",49 "payment due", currentPayable.getPaymentAmount() ); 50 } // end for51 } // end main52 } // end class PayableInterfaceTest

Invoices and Employees processed polymorphically:

invoice:part number: 01234 (seat)quantity: 2price per item: $375.00payment due: $750.00

invoice:part number: 56789 (tire)quantity: 4price per item: $79.95payment due: $319.80

salaried employee: John Smithsocial security number: 111-11-1111weekly salary: $800.00payment due: $800.00

hourly employee: Karen Pricesocial security number: 222-22-2222hourly wage: $16.75; hours worked: 40.00payment due: $670.00

commission employee: Sue Jonessocial security number: 333-33-3333gross sales: $10,000.00; commission rate: 0.06payment due: $600.00

base-salaried commission employee: Bob Lewissocial security number: 444-44-4444gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00new base salary with 10% increase is: $330.00payment due: $530.00

Page 30: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

30 Chapter 10 Object-Oriented Programming: Polymorphism

(Optional) GUI and Graphics Case Study10.1 Modify the MyLine, MyOval and MyRectangle classes of Exercise 8.1 and Exercise 9.1 to cre-ate the class hierarchy in Fig. 10.1. Classes of the MyShape hierarchy should be “smart” shape classesthat know how to draw themselves (if provided with a Graphics object that tells them where todraw). Once the program creates an object from this hierarchy, it can manipulate it polymorphicallyfor the rest of its lifetime as a MyShape.

In your solution, class MyShape in Fig. 10.1 must be abstract. Since MyShape represents anyshape in general, you cannot implement a draw method without knowing exactly what shape it is.The data representing the coordinates and color of the shapes in the hierarchy should be declaredas private members of class MyShape. In addition to the common data, class MyShape shoulddeclare the following methods:

a) A no-argument constructor that sets all the coordinates of the shape to 0 and the colorto Color.BLACK.

b) A constructor that initializes the coordinates and color to the values of the argumentssupplied.

c) Set methods for the individual coordinates and color that allow the programmer to setany piece of data independently for a shape in the hierarchy.

d) Get methods for the individual coordinates and color that allow the programmer to re-trieve any piece of data independently for a shape in the hierarchy.

e) The abstract method

public abstract void draw( Graphics g );

which will be called from the program’s paintComponent method to draw a shape onthe screen.

To ensure proper encapsulation, all data in class MyShape must be private. This requires declar-ing proper set and get methods to manipulate the data. Class MyLine should provide a no-argumentconstructor and a constructor with arguments for the coordinates and color. Classes MyOval andMyRect should provide a no-argument constructor and a constructor with arguments for the coor-dinates, color and determining whether the shape is filled. The no-argument constructor should,in addition to setting the default values, set the shape to be an unfilled shape.

You can draw lines, rectangles and ovals if you know two points in space. Lines require x1, y1,x2 and y2 coordinates. The drawLine method of the Graphics class will connect the two pointssupplied with a line. If you have the same four coordinate values (x1, y1, x2 and y2) for ovals and

Fig. 10.1 | MyShape hierarchy.

java.lang.Object

MyShape

MyOvalMyLine MyRectangle

Page 31: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

(Optional) GUI and Graphics Case Study 31

rectangles, you can calculate the four arguments needed to draw them. Each requires an upper-leftx-coordinate value (the smaller of the two x-coordinate values), an upper-left y-coordinate value(the smaller of the two y coordinate values), a width (the absolute value of the difference betweenthe two x-coordinate values) and a height (the absolute value of the difference between the two y-coordinate values). Rectangles and ovals should also have a filled flag that determines whether todraw the shape as a filled shape.

There should be no MyLine, MyOval or MyRectangle variables in the program—only MyShapevariables that contain references to MyLine, MyOval and MyRectangle objects. The program shouldgenerate random shapes and store them in an array of type MyShape. Method paintComponent

should walk through the MyShape array and draw every shape (i.e., polymorphically calling everyshape’s draw method).

Allow the user to specify (via an input dialog) the number of shapes to generate. The programwill then generate and display the shapes along with a status bar that informs the user how many ofeach shape were created.

ANS:

1 // GCS Exercise 10.1 Solution: MyShape.java2 // Declaration of class MyShape.3 import java.awt.Color;4 import java.awt.Graphics;56 public abstract class MyShape7 {8 private int x1; // x coordinate of first endpoint9 private int y1; // y coordinate of first endpoint

10 private int x2; // x coordinate of second endpoint11 private int y2; // y coordinate of second endpoint12 private Color myColor; // color of this shape1314 // default constructor initializes values with 015 public MyShape()16 {17 this( 0, 0, 0, 0, Color.BLACK ); // call constructor to set values18 } // end MyShape no-argument constructor1920 // constructor21 public MyShape( int x1, int y1, int x2, int y2, Color color )22 {23 setX1( x1 ); // set x coordinate of first endpoint24 setY1( y1 ); // set y coordinate of first endpoint25 setX2( x2 ); // set x coordinate of second endpoint26 setY2( y2 ); // set y coordinate of second endpoint27 setColor( color ); // set the color28 } // end MyShape constructor2930 // set the x-coordinate of the first point31 public void setX1( int x1 )32 {33 this.x1 = ( x1 >= 0 ? x1 : 0 );34 } // end method setX13536 // get the x-coordinate of the first point37 public int getX1()

Page 32: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

32 Chapter 10 Object-Oriented Programming: Polymorphism

38 {39 return x1;40 } // end method getX14142 // set the x-coordinate of the second point43 public void setX2( int x2 )44 {45 this.x2 = ( x2 >= 0 ? x2 : 0 );46 } // end method setX24748 // get the x-coordinate of the second point49 public int getX2()50 {51 return x2;52 } // end method getX25354 // set the y-coordinate of the first point55 public void setY1( int y1 )56 {57 this.y1 = ( y1 >= 0 ? y1 : 0 );58 } // end method setY15960 // get the y-coordinate of the first point61 public int getY1()62 {63 return y1;64 } // end method getY16566 // set the y-coordinate of the second point67 public void setY2( int y2 )68 {69 this.y2 = ( y2 >= 0 ? y2 : 0 );70 } // end method setY27172 // get the y-coordinate of the second point73 public int getY2()74 {75 return y2;76 } // end method getY27778 // set the color79 public void setColor( Color color )80 {81 myColor = color;82 } // end method setColor8384 // get the color85 public Color getColor()86 {87 return myColor;88 } // end method getColor8990 // abstract draw method91 public abstract void draw( Graphics g );92 } // end class MyShape

Page 33: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

(Optional) GUI and Graphics Case Study 33

1 // GCS Exercise 10.1 Solution: MyLine.java2 // Declaration of class MyLine.3 import java.awt.Color;4 import java.awt.Graphics;56 public class MyLine extends MyShape7 {8 // call default superclass constructor9 public MyLine()

10 {11 super();12 } // end MyLine no-argument constructor1314 // call superclass constructor passing parameters15 public MyLine( int x1, int y1, int x2, int y2, Color color )16 {17 super( x1, y1, x2, y2, color );18 } // end MyLine constructor1920 // draw line in specified color21 public void draw( Graphics g )22 {23 g.setColor( getColor() );24 g.drawLine( getX1(), getY1(), getX2(), getY2() );25 } // end method draw26 } // end class MyLine

1 // GCS Exercise 10.1 Solution: MyOval.java2 // Declaration of class MyOval.3 import java.awt.Color;4 import java.awt.Graphics;56 public class MyOval extends MyShape7 {8 private boolean filled; // whether this shape is filled9

10 // call default superclass constructor11 public MyOval()12 {13 super();14 setFilled( false );15 } // end MyOval no-argument constructor1617 // call superclass constructor passing parameters18 public MyOval( int x1, int y1, int x2, int y2,19 Color color, boolean isFilled )20 {21 super( x1, y1, x2, y2, color );22 setFilled( isFilled );23 } // end MyOval constructor2425 // get upper left x coordinate26 public int getUpperLeftX()

Page 34: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

34 Chapter 10 Object-Oriented Programming: Polymorphism

27 {28 return Math.min( getX1(), getX2() );29 } // end method getUpperLeftX3031 // get upper left y coordinate32 public int getUpperLeftY()33 {34 return Math.min( getY1(), getY2() );35 } // end method getUpperLeftY3637 // get shape width38 public int getWidth()39 {40 return Math.abs( getX2() - getX1() );41 } // end method getWidth4243 // get shape height44 public int getHeight()45 {46 return Math.abs( getY2() - getY1() );47 } // end method getHeight4849 // determines whether this shape is filled50 public boolean isFilled()51 {52 return filled;53 } // end method is filled5455 // sets whether this shape is filled56 public void setFilled( boolean isFilled )57 {58 filled = isFilled;59 } // end method setFilled6061 // draw oval62 public void draw( Graphics g )63 {64 g.setColor( getColor() );6566 if ( isFilled() )67 g.fillOval( getUpperLeftX(), getUpperLeftY(),68 getWidth(), getHeight() );69 else70 g.drawOval( getUpperLeftX(), getUpperLeftY(),71 getWidth(), getHeight() );72 } // end method draw73 } // end class MyOval

1 // GCS Exercise 10.1 Solution: MyRect.java2 // Declaration of class MyRect.3 import java.awt.Color;4 import java.awt.Graphics;5

Page 35: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

(Optional) GUI and Graphics Case Study 35

6 public class MyRect extends MyShape7 {8 private boolean filled; // whether this shape is filled9

10 // call default superclass constructor11 public MyRect()12 {13 super();14 setFilled( false );15 } // end MyRect no-argument constructor1617 // call superclass constructor passing parameters18 public MyRect( int x1, int y1, int x2, int y2,19 Color color, boolean isFilled )20 {21 super( x1, y1, x2, y2, color );22 setFilled( isFilled );23 } // end MyRect constructor2425 // get upper left x coordinate26 public int getUpperLeftX()27 {28 return Math.min( getX1(), getX2() );29 } // end method getUpperLeftX3031 // get upper left y coordinate32 public int getUpperLeftY()33 {34 return Math.min( getY1(), getY2() );35 } // end method getUpperLeftY3637 // get shape width38 public int getWidth()39 {40 return Math.abs( getX2() - getX1() );41 } // end method getWidth4243 // get shape height44 public int getHeight()45 {46 return Math.abs( getY2() - getY1() );47 } // end method getHeight4849 // determines whether this shape is filled50 public boolean isFilled()51 {52 return filled;53 } // end method is filled5455 // sets whether this shape is filled56 public void setFilled( boolean isFilled )57 {58 filled = isFilled;59 } // end method setFilled

Page 36: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

36 Chapter 10 Object-Oriented Programming: Polymorphism

6061 // draw rectangle62 public void draw( Graphics g )63 {64 g.setColor( getColor() );6566 if ( isFilled() )67 g.fillRect( getUpperLeftX(), getUpperLeftY(),68 getWidth(), getHeight() );69 else70 g.drawRect( getUpperLeftX(), getUpperLeftY(),71 getWidth(), getHeight() );72 } // end method draw73 } // end class MyRect

1 // GCS Exercise 10.1 Solution: DrawPanel.java2 // Program randomly draws shapes.3 import java.awt.Color;4 import java.awt.Graphics;5 import java.util.Random;6 import javax.swing.JPanel;78 public class DrawPanel extends JPanel9 {

10 private Random randomNumbers = new Random();11 private MyShape shapes[]; // array containing all the shapes12 private int shapeCount[]; // statistic on the number of each shape1314 // String containing shape statistic information15 private String statusText;1617 // constructor that takes in the number of shapes18 public DrawPanel( int numberShapes )19 {20 setBackground( Color.WHITE );2122 shapes = new MyShape[ numberShapes ];23 shapeCount = new int[ 3 ];2425 for ( int i = 0; i < shapes.length; i++ )26 {27 // generate random coordinates28 int x1 = randomNumbers.nextInt( 450 );29 int x2 = randomNumbers.nextInt( 450 );30 int y1 = randomNumbers.nextInt( 450 );31 int y2 = randomNumbers.nextInt( 450 );3233 // generate a random color34 Color color = new Color ( randomNumbers.nextInt( 256 ),35 randomNumbers.nextInt( 256 ), randomNumbers.nextInt( 256 ) );3637 // get filled property38 boolean filled = randomNumbers.nextBoolean();

Page 37: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

(Optional) GUI and Graphics Case Study 37

3940 int shapeType = randomNumbers.nextInt( 3 );41 ++shapeCount[ shapeType ];4243 switch ( shapeType )44 {45 case 0: // line46 shapes[ i ] = new MyLine( x1, y1, x2, y2, color );47 break;48 case 1: // oval49 shapes[ i ] = new MyOval( x1, y1, x2, y2, color, filled );50 break;51 case 2: // rectangle52 shapes[ i ] = new MyRect( x1, y1, x2, y2, color, filled );53 break;54 } // end switch55 } // end for5657 // create string for the status bar label58 statusText = String.format( " %s: %d, %s: %d, %s: %d",59 "Lines", shapeCount[ 0 ], "Ovals", shapeCount[ 1 ],60 "Rectangles", shapeCount[ 2 ] );61 } // end DrawPanel constructor6263 // returns a label containing shape statistics for this panel64 public String getLabelText()65 {66 return statusText;67 } // end method getStatusLabel6869 // draw shapes using polymorphism70 public void paintComponent( Graphics g )71 {72 super.paintComponent( g );7374 for ( MyShape shape : shapes )75 shape.draw( g );76 } // end method paintComponent77 } // end class DrawPanel

1 // GCS Exercise 10.1 Solution: TestDraw.java2 // Test application to display a DrawPanel3 import java.awt.BorderLayout;4 import javax.swing.JLabel;5 import javax.swing.JOptionPane;6 import javax.swing.JFrame;78 public class TestDraw9 {

10 public static void main( String args[] )11 {12 // Ask the user to enter the number of shapes13 int shapes = Integer.parseInt(

Page 38: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

38 Chapter 10 Object-Oriented Programming: Polymorphism

14 JOptionPane.showInputDialog( "Number of shapes" ) );1516 DrawPanel panel = new DrawPanel( shapes ); 17 JFrame application = new JFrame();1819 // Create a label containing the shape information20 JLabel statusLabel = new JLabel( panel.getLabelText() );2122 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );2324 application.add( panel ); // add drawing to CENTER by default25 // Add the status label to the SOUTH (bottom) of the frame26 application.add( statusLabel, BorderLayout.SOUTH );2728 application.setSize( 500, 500 );29 application.setVisible( true );30 } // end main31 } // end class TestDraw

Page 39: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

(Optional) GUI and Graphics Case Study 39

10.2 (Drawing Application Modification) In Exercise 10.1, you created a MyShape hierarchy inwhich classes MyLine, MyOval and MyRectangle extend MyShape directly. If your hierarchy was prop-erly designed, you should be able to see the similarities between the MyOval and MyRectangle classes.Redesign and reimplement the code for the MyOval and MyRectangle classes to “factor out” the com-mon features into the abstract class MyBoundedShape to produce the hierarchy in Fig. 10.2.

Class MyBoundedShape should declare two constructors that mimic the constructors of classMyShape, only with an added parameter to set whether the shape is filled. Class MyBoundedShapeshould also declare get and set methods for manipulating the filled flag and methods that calculatethe upper-left x-coordinate, upper-left y-coordinate, width and height. Remember, the valuesneeded to draw an oval or a rectangle can be calculated from two (x, y) coordinates. If designedproperly, the new MyOval and MyRectangle classes should each have two constructors and a draw

method.ANS:

Fig. 10.2 | MyShape hierarchy with MyBoundedShape.

1 // GCS Exercise 10.2 Solution: MyShape.java2 // Declaration of class MyShape.3 import java.awt.Color;4 import java.awt.Graphics;56 public abstract class MyShape7 {8 private int x1; // x coordinate of first endpoint9 private int y1; // y coordinate of first endpoint

10 private int x2; // x coordinate of second endpoint11 private int y2; // y coordinate of second endpoint12 private Color myColor; // color of this shape1314 // default constructor initializes values with 015 public MyShape()16 {17 this( 0, 0, 0, 0, Color.BLACK ); // call constructor to set values

java.lang.Object

MyShape

MyLine MyBoundedShape

MyOval MyRectangle

Page 40: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

40 Chapter 10 Object-Oriented Programming: Polymorphism

18 } // end MyShape no-argument constructor1920 // constructor21 public MyShape( int x1, int y1, int x2, int y2, Color color )22 {23 setX1( x1 ); // set x coordinate of first endpoint24 setY1( y1 ); // set y coordinate of first endpoint25 setX2( x2 ); // set x coordinate of second endpoint26 setY2( y2 ); // set y coordinate of second endpoint27 setColor( color ); // set the color28 } // end MyShape constructor2930 // set the x-coordinate of the first point31 public void setX1( int x1 )32 {33 this.x1 = ( x1 >= 0 ? x1 : 0 );34 } // end method setX13536 // get the x-coordinate of the first point37 public int getX1()38 {39 return x1;40 } // end method getX14142 // set the x-coordinate of the second point43 public void setX2( int x2 )44 {45 this.x2 = ( x2 >= 0 ? x2 : 0 );46 } // end method setX24748 // get the x-coordinate of the second point49 public int getX2()50 {51 return x2;52 } // end method getX25354 // set the y-coordinate of the first point55 public void setY1( int y1 )56 {57 this.y1 = ( y1 >= 0 ? y1 : 0 );58 } // end method setY15960 // get the y-coordinate of the first point61 public int getY1()62 {63 return y1;64 } // end method getY16566 // set the y-coordinate of the second point67 public void setY2( int y2 )68 {69 this.y2 = ( y2 >= 0 ? y2 : 0 );70 } // end method setY271

Page 41: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

(Optional) GUI and Graphics Case Study 41

72 // get the y-coordinate of the second point73 public int getY2()74 {75 return y2;76 } // end method getY27778 // set the color79 public void setColor( Color color )80 {81 myColor = color;82 } // end method setColor8384 // get the color85 public Color getColor()86 {87 return myColor;88 } // end method getColor8990 // abstract draw method91 public abstract void draw( Graphics g );92 } // end class MyShape

1 // GCS Exercise 10.2 Solution: MyLine.java2 // Declaration of class MyLine.3 import java.awt.Color;4 import java.awt.Graphics;56 public class MyLine extends MyShape7 {8 // call default superclass constructor9 public MyLine()

10 {11 super();12 } // end MyLine no-argument constructor1314 // call superclass constructor passing parameters15 public MyLine( int x1, int y1, int x2, int y2, Color color )16 {17 super( x1, y1, x2, y2, color );18 } // end MyLine constructor1920 // draw line in specified color21 public void draw( Graphics g )22 {23 g.setColor( getColor() );24 g.drawLine( getX1(), getY1(), getX2(), getY2() );25 } // end method draw26 } // end class MyLine

1 // GCS Exercise 10.2 Solution: MyBoundedShape.java2 // Declaration of class MyBoundedShape.

Page 42: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

42 Chapter 10 Object-Oriented Programming: Polymorphism

3 import java.awt.Color;4 import java.awt.Graphics;56 public abstract class MyBoundedShape extends MyShape7 {8 private boolean filled; // whether this shape is filled9

10 // call default superclass constructor11 public MyBoundedShape()12 {13 super();14 setFilled( false );15 } // end MyBoundedShape no-argument constructor1617 // call superclass constructor passing parameters18 public MyBoundedShape( int x1, int y1, int x2, int y2,19 Color color, boolean isFilled )20 {21 super( x1, y1, x2, y2, color );22 setFilled( isFilled );23 } // end MyBoundedShape constructor2425 // get upper left x coordinate26 public int getUpperLeftX()27 {28 return Math.min( getX1(), getX2() );29 } // end method getUpperLeftX3031 // get upper left y coordinate32 public int getUpperLeftY()33 {34 return Math.min( getY1(), getY2() );35 } // end method getUpperLeftY3637 // get shape width38 public int getWidth()39 {40 return Math.abs( getX2() - getX1() );41 } // end method getWidth4243 // get shape height44 public int getHeight()45 {46 return Math.abs( getY2() - getY1() );47 } // end method getHeight4849 // determines whether this shape is filled50 public boolean isFilled()51 {52 return filled;53 } // end method is filled5455 // sets whether this shape is filled56 public void setFilled( boolean isFilled )

Page 43: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

(Optional) GUI and Graphics Case Study 43

57 {58 filled = isFilled;59 } // end method setFilled60 } // end class MyBoundedShape

1 // GCS Exercise 10.2 Solution: MyOval.java2 // Declaration of class MyOval.3 import java.awt.Color;4 import java.awt.Graphics;56 public class MyOval extends MyBoundedShape7 {8 // call default superclass constructor9 public MyOval()

10 {11 super();12 } // end MyOval no-argument constructor1314 // call superclass constructor passing parameters15 public MyOval( int x1, int y1, int x2, int y2,16 Color color, boolean isFilled )17 {18 super( x1, y1, x2, y2, color, isFilled );19 } // end MyOval constructor2021 // draw oval22 public void draw( Graphics g )23 {24 g.setColor( getColor() );2526 if ( isFilled() )27 g.fillOval( getUpperLeftX(), getUpperLeftY(),28 getWidth(), getHeight() );29 else30 g.drawOval( getUpperLeftX(), getUpperLeftY(),31 getWidth(), getHeight() );32 } // end method draw33 } // end class MyOval

1 // GCS Exercise 10.2 Solution: MyRect.java2 // Declaration of class MyRect.3 import java.awt.Color;4 import java.awt.Graphics;56 public class MyRect extends MyBoundedShape7 {8 // call default superclass constructor9 public MyRect()

10 {11 super();12 } // end MyRect no-argument constructor

Page 44: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

44 Chapter 10 Object-Oriented Programming: Polymorphism

1314 // call superclass constructor passing parameters15 public MyRect( int x1, int y1, int x2, int y2,16 Color color, boolean isFilled )17 {18 super( x1, y1, x2, y2, color, isFilled );19 } // end MyRect constructor2021 // draw rectangle22 public void draw( Graphics g )23 {24 g.setColor( getColor() );2526 if ( isFilled() )27 g.fillRect( getUpperLeftX(), getUpperLeftY(),28 getWidth(), getHeight() );29 else30 g.drawRect( getUpperLeftX(), getUpperLeftY(),31 getWidth(), getHeight() );32 } // end method draw33 } // end class MyRect

1 // GCS Exercise 10.2 Solution: DrawPanel.java2 // Program randomly draws shapes.3 import java.awt.Color;4 import java.awt.Graphics;5 import java.util.Random;6 import javax.swing.JPanel;78 public class DrawPanel extends JPanel9 {

10 private Random randomNumbers = new Random();11 private MyShape shapes[]; // array containing all the shapes12 private int shapeCount[]; // statistic on the number of each shape1314 // String containing shape statistic information15 private String statusText;1617 // constructor that takes in the number of shapes18 public DrawPanel( int numberShapes )19 {20 setBackground( Color.WHITE );2122 shapes = new MyShape[ numberShapes ];23 shapeCount = new int[ 3 ];2425 for ( int i = 0; i < shapes.length; i++ )26 {27 // generate random coordinates28 int x1 = randomNumbers.nextInt( 450 );29 int x2 = randomNumbers.nextInt( 450 );30 int y1 = randomNumbers.nextInt( 450 );31 int y2 = randomNumbers.nextInt( 450 );

Page 45: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

(Optional) GUI and Graphics Case Study 45

3233 // generate a random color34 Color color = new Color ( randomNumbers.nextInt( 256 ),35 randomNumbers.nextInt( 256 ), randomNumbers.nextInt( 256 ) );3637 // get filled property38 boolean filled = randomNumbers.nextBoolean();3940 int shapeType = randomNumbers.nextInt( 3 );41 ++shapeCount[ shapeType ];4243 switch ( shapeType )44 {45 case 0: // line46 shapes[ i ] = new MyLine( x1, y1, x2, y2, color );47 break;48 case 1: // oval49 shapes[ i ] = new MyOval( x1, y1, x2, y2, color, filled );50 break;51 case 2: // rectangle52 shapes[ i ] = new MyRect( x1, y1, x2, y2, color, filled );53 break;54 } // end switch55 } // end for5657 // create string for the status bar label58 statusText = String.format( " %s: %d, %s: %d, %s: %d",59 "Lines", shapeCount[ 0 ], "Ovals", shapeCount[ 1 ],60 "Rectangles", shapeCount[ 2 ] );61 } // end DrawPanel constructor6263 // returns a label containing shape statistics for this panel64 public String getLabelText()65 {66 return statusText;67 } // end method getStatusLabel6869 // draw shapes using polymorphism70 public void paintComponent( Graphics g )71 {72 super.paintComponent( g );7374 for ( MyShape shape : shapes )75 shape.draw( g );76 } // end method paintComponent77 } // end class DrawPanel

1 // GCS Exercise 10.2 Solution: TestDraw.java2 // Test application to display a DrawPanel3 import java.awt.BorderLayout;4 import javax.swing.JLabel;5 import javax.swing.JOptionPane;6 import javax.swing.JFrame;7

Page 46: Object Oriented Programming Polymorphismread.pudn.com/downloads309/ebook/1371379/solved... · 2007-06-13 · 2 Chapter 10Object-Oriented Programming: Polymorphism Self-Review Exercises

46 Chapter 10 Object-Oriented Programming: Polymorphism

8 public class TestDraw9 {

10 public static void main( String args[] )11 {12 // Ask the user to enter the number of shapes13 int shapes = Integer.parseInt(14 JOptionPane.showInputDialog( "Number of shapes" ) );1516 DrawPanel panel = new DrawPanel( shapes ); 17 JFrame application = new JFrame();1819 // Create a label containing the shape information20 JLabel statusLabel = new JLabel( panel.getLabelText() );2122 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );2324 application.add( panel ); // add drawing to CENTER by default25 // Add the status label to the SOUTH (bottom) of the frame26 application.add( statusLabel, BorderLayout.SOUTH );2728 application.setSize( 500, 500 );29 application.setVisible( true );30 } // end main31 } // end class TestDraw