AhmadLang / Java, How To Program, 2004
.pdf
[Page 411 (continued)]
Answers to Self-Review Exercises
8.1 a) -d. b) format. c) shadows. d) finalize. e) single-type-import. f) default constructor. g) toString. h) accessor methods, query methods. i) predicate. j) values. k) has-a. l) enum. m) static. n) single static import. o) principle of least privilege. p) final. q) abstract data type (ADT). r) package declaration. s) type- import-on-demand. t) class loader. u) -classpath, CLASSPATH. v) mutator methods. w) static import on demand. x) public services, public interface. y) gc. z) consistent data.
[Page 411 (continued)]
Exercises
8.2Explain the notion of package access in Java. Explain the negative aspects of package access.
8.3What happens when a return type, even void, is specified for a constructor?
8.4(Rectangle Class) Create a class Rectangle. The class has attributes length and width, each of which defaults to 1. It has methods that calculate the perimeter and the area of the rectangle. It has set and get methods for both length and width. The set methods should verify that length and width are each floating-point numbers larger than 0.0 and less than 20.0. Write a program to test class Rectangle.
8.5(Modifying the Internal Data Representation of a Class) It would be perfectly reasonable for the Time2 class of Fig. 8.5 to represent the time internally as the number of seconds since midnight rather than the three integer values hour, minute and second. Clients could use the same public methods and get the same results. Modify the Time2 class of Fig. 8.5 to implement the Time2 as the number of seconds since midnight and show that no change is visible to the clients of the class.
[Page 412]
8.6(Savings Account Class) Create class SavingsAccount. Use a static variable annualInterestRate to store the annual interest rate for all account holders. Each object of the class contains a private instance variable savingsBalance indicating the amount the saver currently has on deposit. Provide method calculateMonthlyInterest to calculate the monthly interest by multiplying the savingsBalance by annualInterestRate divided by 12this interest should be added to savingsBalance. Provide a static method modifyInterestRate that sets the annualInterestRate to a new value. Write a program to test class SavingsAccount. Instantiate two savingsAccount objects, saver1 and saver2, with balances of $2000.00 and $3000.00, respectively. Set annualInterestRate to 4%, then calculate the monthly interest and print the new balances for both savers. Then set the annualInterestRate to 5%, calculate the next month's interest and print the new balances for both savers.
8.7(Enhancing Class Time2) Modify class Time2 of Fig. 8.5 to include a tick method that increments the time stored in a Time2 object by one second. Provide method incrementMinute to increment the minute and method incrementHour to increment the hour. The Time2 object should always remain in a consistent state. Write a program that tests the tick method, the increment-Minute method and the incrementHour method to ensure that they work correctly. Be sure to test the following cases:
a.incrementing into the next minute,
b.incrementing into the next hour and
c.incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).
8.8(Enhancing Class Date) Modify class Date of Fig. 8.7 to perform error checking on the initializer values for instance variables month, day and year (currently it validates only the month and day). Provide a method nexTDay to increment the day by one. The Date object should always remain in a consistent state. Write a program that tests the nexTDay method in a loop that prints the date during each iteration of the loop to illustrate that the nexTDay method works correctly. Test the following cases:
a.incrementing into the next month and
b.incrementing into the next year.
8.9(Returning Error Indicators from Methods) Modify the set methods in class Time2 of Fig. 8.5 to return appropriate error values if an attempt is made to set one of the instance variables hour, minute or second of an object of class Time to an invalid value. [Hint: Use boolean return types on each method.] Write a program that tests these new set methods and outputs error messages when incorrect values are supplied.
8.10Rewrite Fig. 8.14 to use a separate import declaration for each static member of class Math that is used in the example.
8.11Write an enum type TRafficLight, whose constants (RED, GREEN, YELLOW) take one parameterthe duration of the light. Write a program to test the trafficLight enum so that it displays the enum constants and their durations.
8.12(Complex Numbers) Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have the form
where i is
Write a program to test your class. Use floating-point variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it is declared. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform the following operations:
[Page 413]
a.Add two Complex numbers: The real parts are added together and the imaginary parts are added together.
b.Subtract two Complex numbers: The real part of the right operand is subtracted from the real part of the left operand, and the imaginary part of the right operand is subtracted from the imaginary part of the left operand.
c.Print Complex numbers in the form (a, b), where a is the real part and b is the imaginary part.
8.13(Date and Time Class) Create class DateAndTime that combines the modified Time2 class of Exercise 8.7 and the modified Date class of Exercise 8.8. Modify method incrementHour to call method nextday if the time is incremented into the next day. Modify methods toStandardString and toUniversalString to output the date in addition to the time. Write a program to test the new class DateAndTime. Specifically, test incrementing the time to the next day.
8.14(Enhanced Rectangle Class) Create a more sophisticated Rectangle class than the one you created in Exercise 8.4. This class stores only the Cartesian coordinates of the four corners of the rectangle. The constructor calls a set method that accepts four sets of coordinates and verifies that each of these is in the first quadrant with no single x- or y-coordinate larger than 20.0. The set method also verifies that the supplied coordinates specify a rectangle. Provide methods to calculate the length, width, perimeter and area. The length is the larger of the two dimensions. Include a
predicate method isSquare which determines whether the rectangle is a square. Write
a program to test class Rectangle.
8.15(Set of Integers) Create class IntegerSet. Each IntegerSet object can hold integers in the range 0100. The set is represented by an array of booleans. Array element a[i] is true if integer i is in the set. Array element a[j] is false if integer j is not in the set. The no-argument constructor initializes the Java array to the "empty set" (i.e., a set whose array representation contains all false values).
Provide the following methods: Method union creates a third set that is the settheoretic union of two existing sets (i.e., an element of the third set's array is set to TRue if that element is true in either or both of the existing setsotherwise, the element of the third set is set to false). Method intersection creates a third set which is the set-theoretic intersection of two existing sets (i.e., an element of the third set's array is set to false if that element is false in either or both of the existing setsotherwise, the element of the third set is set to true). Method insertElement inserts a new integer k into a set (by setting a[k] to true). Method deleteElement deletes integer m (by setting a[m] to false). Method toSetString returns a string containing a set as a list of numbers separated by spaces. Include only those elements that are present in the set. Use --- to represent an empty set. Method isEqualTo determines whether two sets are equal. Write a program to test class IntegerSet. Instantiate several IntegerSet objects. Test that all your methods work properly.
8.16(Date Class) Create class Date with the following capabilities:
a. Output the date in multiple formats, such as
MM/DD/YYYY
June 14, 1992
DDDYYYY
b.Use overloaded constructors to create Date objects initialized with dates of the formats in part (a). In the first case the constructor should receive three integer values. In the second case it should receive a String and two integer values. In the third case it should receive two integer values, the first of which represents the day number in the year. [Hint: To convert the string representation of the month to a numeric value, compare strings using the equals method. For example, if s1 and s2 are strings, the method call s1.equals( s2 ) returns true if the strings are identical and otherwise returns false.]
[Page 414]
8.17(Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private instance variables of the classthe numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should store the fraction in reduced form. The fraction
2/4
is equivalent to 1/2 and would be stored in the object as 1 in the numerator and 2 in the denominator. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform each of the following operations:
a.Add two Rational numbers: The result of the addition should be stored in reduced form.
b.Subtract two Rational numbers: The result of the subtraction should be stored in reduced form.
c.Multiply two Rational numbers: The result of the multiplication should be stored in reduced form.
d.Divide two Rational numbers: The result of the division should be stored in reduced form.
e.Print Rational numbers in the form a/b, where a is the numerator and b is the denominator.
f.Print Rational numbers in floating-point format. (Consider providing formatting capabilities that enable the user of the class to specify the number of digits of precision to the right of the decimal point.)
8.18(Huge Integer Class) Create a class HugeInteger which uses a 40-element array of digits to store integers as large as 40 digits each. Provide methods input, output, add and subtract. For comparing HugeInteger objects, provide the following methods: isEqualTo, isNotEqualTo, isGreaterThan, isLessThan, isGreaterThanOrEqualTo and isLessThanOrEqualTo. Each of these is a predicate method that returns true if the relationship holds between the two HugeInteger objects and returns false if the relationship does not hold. Provide a predicate method isZero. If you feel ambitious, also provide methods multiply, divide and remainder. [Note: Primitive boolean values can be output as the word "true" or the word "false" with format specifier %b.]
8.19(Tic-Tac-Toe) Create a class TicTacToe that will enable you to write a complete program to play the game of Tic-Tac-Toe. The class contains a private 3-by-3 twodimensional array of integers. The constructor should initialize the empty board to all zeros. Allow two human players. Wherever the first player moves, place a 1 in the specified square, and place a 2 wherever the second player moves. Each move must be to an empty square. After each move, determine whether the game has been won and whether it is a draw. If you feel ambitious, modify your program so that the computer makes the moves for one of the players. Also, allow the player to specify whether he or she wants to go first or second. If you feel exceptionally ambitious, develop a program that will play three-dimensional Tic-Tac-Toe on a 4-by-4-by-4 board [Note: This is a challenging project that could take many weeks of effort!].
[Page 415]
Chapter 9. Object-Oriented Programming:
Inheritance
Say not you know another entirely, till you have divided an inheritance with him.
Johann Kasper Lavater
This method is to define as the number of a class the class of all classes similar to the given class.
Bertrand Russell
Good as it is to inherit a library, it is better to collect one.
Augustine Birrell
Save base authority from others' books.
William Shakespeare
OBJECTIVES
In this chapter you will learn:
How inheritance promotes software reusability.
The notions of superclasses and subclasses.
To use keyword extends to create a class that inherits attributes and behaviors from another class.
To use access modifier protected to give subclass methods access to superclass members.
To access superclass members with super.
How constructors are used in inheritance hierarchies.
The methods of class Object, the direct or indirect superclass of all classes in Java.
[Page 416]
Outline
9.1 Introduction
9.2 Superclasses and Subclasses
9.3 protected Members
9.4 Relationship between Superclasses and Subclasses
9.4.1 Creating and Using a CommissionEmployee Class
9.4.2 Creating a BasePlusCommissionEmployee Class without Using Inheritance
9.4.3 Creating a CommissionEmployeeBasePlusCommissionEmployee Inheritance
Hierarchy
9.4.4 CommissionEmployeeBasePlusCommissionEmployee Inheritance Hierarchy Using protected Instance Variables
9.4.5 CommissionEmployeeBasePlusCommissionEmployee Inheritance Hierarchy Using private Instance Variables
9.5 Constructors in Subclasses
9.6 Software Engineering with Inheritance
9.7 Object Class
9.8 (Optional) GUI and Graphics Case Study: Displaying Text and Images Using Labels
9.9 Wrap-Up
Summary
Terminology
Self-Review Exercises
Answers to Self-Review Exercises
Exercises
[Page 416 (continued)]
9.1. Introduction
This chapter continues our discussion of object-oriented programming (OOP) by introducing one of its primary featuresinheritance, which is a form of software reuse in which a new class is created by absorbing an existing class's members and embellishing them with new or modified capabilities. With inheritance, programmers save time during program development by reusing proven and debugged highquality software. This also increases the likelihood that a system will be implemented effectively.
When creating a class, rather than declaring completely new members, the programmer can designate that the new class should inherit the members of an existing class. The existing class is called the superclass, and the new class is the subclass. (The C++ programming language refers to the superclass as the base class and the subclass as the derived class.) Each subclass can become the superclass for future subclasses.
A subclass normally adds its own fields and methods. Therefore, a subclass is more specific than its superclass and represents a more specialized group of objects. Typically, the subclass exhibits the behaviors of its superclass and additional behaviors that are specific to the subclass.
The direct superclass is the superclass from which the subclass explicitly inherits. An indirect superclass is any class above the direct superclass in the class hierarchy, which defines the inheritance relationships between classes. In Java, the class hierarchy begins with class Object (in package java.lang), which every class in Java directly or indirectly extends (or "inherits from"). Section 9.7 lists the methods of class Object, which every other class inherits. In the case of single inheritance, a class is derived from one direct superclass. Java, unlike C++, does not support multiple inheritance (which occurs when a class is derived from more than one direct superclass). In Chapter 10, Object-Oriented Programming: Polymorphism, we explain how Java programmers can use interfaces to realize many of the benefits of multiple inheritance while avoiding the associated problems.
[Page 417]
Experience in building software systems indicates that significant amounts of code deal with closelyrelated special cases. When programmers are preoccupied with special cases, the details can obscure the big picture. With object-oriented programming, programmers focus on the commonalities among objects in the system rather than on the special cases.
We distinguish between the "is-a" relationship and the "has-a" relationship. "Is-a" represents inheritance. In an "is-a" relationship, an object of a subclass can also be treated as an object of its superclass. For example, a car is a vehicle. By contrast, "has-a" represents composition (see Chapter 8). In a "has-a" relationship, an object contains one or more object references as members. For example, a car has a steering wheel (and a car object has a reference to a steering wheel object).
New classes can inherit from classes in class libraries. Organizations develop their own class libraries and can take advantage of others available worldwide. Some day, most new software likely will be constructed from standardized reusable components, just as automobiles and most computer hardware are constructed today. This will facilitate the development of more powerful, abundant and economical software.
[Page 417 (continued)]
9.2. Superclasses and Subclasses
Often, an object of one class "is an" object of another class as well. For example, in geometry, a rectangle is a quadrilateral (as are squares, parallelograms and trapezoids). Thus, in Java, class Rectangle can be said to inherit from class Quadrilateral. In this context, class Quadrilateral is a superclass and class Rectangle is a subclass. A rectangle is a specific type of quadrilateral, but it is incorrect to claim that every quadrilateral is a rectanglethe quadrilateral could be a parallelogram or some other shape. Figure 9.1 lists several simple examples of superclasses and subclassesnote that superclasses tend to be "more general" and subclasses tend to be "more specific."
|
Figure 9.1. Inheritance examples. |
Superclass |
Subclasses |
|
|
Student |
GraduateStudent, UndergraduateStudent |
Shape |
Circle, TRiangle, Rectangle |
Loan |
CarLoan, HomeImprovementLoan, MortgageLoan |
Employee |
Faculty, Staff |
BankAccount |
CheckingAccount, SavingsAccount |
|
|
Because every subclass object "is an" object of its superclass, and one superclass can have many subclasses, the set of objects represented by a superclass is typically larger than the set of objects represented by any of its subclasses. For example, the superclass Vehicle represents all vehicles, including cars, trucks, boats, bicycles and so on. By contrast, subclass Car represents a smaller, more specific subset of vehicles.
[Page 418]
Inheritance relationships form tree-like hierarchical structures. A superclass exists in a hierarchical relationship with its subclasses. When classes participate in inheritance relationships, they become "affiliated" with other classes. A class becomes either a superclass, supplying members to other classes, or a subclass, inheriting its members from other classes. In some cases, a class is both a superclass and a subclass.
Let us develop a sample class hierarchy (Fig. 9.2), also called an inheritance hierarchy. A university community has thousands of members, including employees, students and alumni. Employees are either faculty members or staff members. Faculty members are either administrators (such as deans and department chairpersons) or teachers. Note that the hierarchy could contain many other classes. For example, students can be graduate or undergraduate students. Undergraduate students can be freshmen, sophomores, juniors or seniors.
Figure 9.2. Inheritance hierarchy for university CommunityMembers.
[View full size image]
