Exercises
9.3 |
Many programs written with inheritance could be written with composition instead, and vice versa. Rewrite class BasePlusCommissionEmployee4 (Fig. 9.13) of the CommissionEmployee3BasePlusCommissionEmployee4 hierarchy to use composition rather than inheritance. After you do this, assess the relative merits of the two approaches for the CommissionEmployee3 and BasePlusCommissionEmployee4 problems, as well as for object-oriented programs in general. Which approach is more natural? Why?
|
9.4 |
Discuss the ways in which inheritance promotes software reuse, saves time during program development and helps prevent errors.
|
9.5 |
Draw an inheritance hierarchy for students at a university similar to the hierarchy shown in Fig. 9.2. Use Student as the superclass of the hierarchy, then extend Student with classes UndergraduateStudent and GraduateStudent. Continue to extend the hierarchy as deep (i.e., as many levels) as possible. For example, Freshman, Sophomore, Junior and Senior might extend UndergraduateStudent, and DoctoralStudent and MastersStudent might be subclasses of GraduateStudent. Afterdrawing the hierarchy, discuss the relationships that exist between the classes. [Note: You do not need to write any code for this exercise.]
|
9.6 |
The world of shapes is much richer than the shapes included in the inheritance hierarchy of Fig. 9.3. Write down all the shapes you can think ofboth two-dimensional and three-dimensionaland form them into a more complete Shape hierarchy with as many levels as possible. Your hierarchy should have class Shape at the top. Class TwoDimensionalShape and class ThreeDimensionalShape should extend Shape. Add additional subclasses, such as Quadrilateral and Sphere, at their correct locations in the hierarchy as necessary.
|
9.7 |
Some programmers prefer not to use protected access, because they believe it breaks the encapsulation of the superclass. Discuss the relative merits of using protected access vs. using private access in superclasses.
|
9.8 |
Write an inheritance hierarchy for classes Quadrilateral, TRapezoid, Parallelogram, Rectangle and Square. Use Quadrilateral as the superclass of the hierarchy. Make the hierarchy as deep (i.e., as many levels) as possible. Specify the instance variables and methods for each class. The private instance variables of Quadrilateral should be the x-y coordinate pairs for the four endpoints of the Quadrilateral. Write a program that instantiates objects of your classes and outputs each object's area (except Quadrilateral).
|
|