inheritance lab manual
TRANSCRIPT
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 1/42
9Object-Oriented
Programming:Inheritance
O B J E C T I V E S
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 attributesand behaviors from another class.
■ To use access modifier protected to give subclass methodsaccess 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 ofall classes in Java.
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 3/42
Chapter 9 Object-Oriented Programming: Inheritance 3
Name: Date:
Section:
Assignment Checklist
Exercises Assigned: Circle assignments Date Due
Prelab Activities
Matching YES NO
Fill in the Blank 12, 13, 14, 15, 16, 17, 18, 19, 20,21
Short Answer 22, 23, 24, 25, 26 Correct the Code 27, 28, 29
Lab Exercise
Exercise 1 — Employee Hierarchy YES NO
Follow-Up Question and Activity 1
Postlab Activities
Coding Exercises 1, 2, 3
Programming Challenge 1
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 5/42
Chapter 9 Object-Oriented Programming: Inheritance 5
Prelab Activities
Name: Date:
Section:
Matching
After reading Chapter 9 of Java How to Program: 8/e , answer the given questions. The questions are intended totest and reinforce your understanding of key concepts. You may answer the questions before or during the lab.
For each term in the left column, write the letter for the description from the right column that best matches theterm.
Term Description
D
K
G
J
H
C
A
I
B
F
E
1. extends
2. Object class
3. class hierarchy
4. protected
5. inheritance
6. super
7. direct superclass
8. brittle software
9. override10. clone method
11. indirect superclass
a) A subclass’s immediate superclass extends.
b) Term used to describe the case when a subclass method is de-fined with the same signature as a superclass method.
c) Keyword used to refer to an object’s superclass members.
d) Indicates that a subclass will inherit from a particular superclass.
e) A class that a subclass does not directly extend; however, the sub-class still has an is-a relationship with the class.
f) A protected method that takes no arguments. It returns a copy of the object on which it is called.
g) A set of classes related by inheritance.h) Is-a relationship.
i) A small change in the superclass can “break” subclass implemen-tations.
j) Such members can be accessed in the class in which they are de-fined, and in all subclasses of that class.
k) Superclass of all Java classes.
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 7/42
Prelab Activities Name:
Fill in the Blank
Chapter 9 Object-Oriented Programming: Inheritance 7
Name: Date:
Section:
Fill in the Blank
Fill in the blanks for each of the following statements:
12. A subclass can explicitly invoke a constructor of its superclass by using the superclass constructor call syn-tax—keyword super followed by a set of parentheses containing the superclass constructor’s arguments.
13. Every object of a subclass is also an object of that class’s superclass . However, a superclass object is notan object of any of its subclasses .
14. In a(n) has-a relationship, an object has a reference to an object of another class as a member.
15. In a(n) is-a relationship, an object of a subclass type may also be treated as an object of the superclass type.
16. Some day, most new software likely will be constructed from standardized reusable components , just asautomobiles and most computer hardware are constructed today.
17. A subclass cannot directly access private members of its superclass.
18. The direct superclass of a subclass is the superclass from which the subclass inherits.
19. With single inheritance, a class is derived from one superclass. Java does not support multiple inheritance.
20. A subclass inherits the members of its superclass that are declared with the access specifiers public andprotected .
21. The toString method of class Object is normally overridden by a subclass.
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 9/42
Prelab Activities Name:
Short Answer
Chapter 9 Object-Oriented Programming: Inheritance 9
Name: Date:
Section:
Short Answer
In the space provided, answer each of the given questions. Your answers should be concise; aim for two or threesentences.
22. How does inheritance promote software reusability?
Inheritance enables programmers to create new classes from existing classes by absorbing their attributes and be-
haviors, and adding capabilities the new classes require. Inheritance also takes advantage of class relationships where objects of a certain class have the same characteristics.
23. Explain protected member access.
The protected members of a class are accessible to the class in which they are defined, all subclasses of that classand other classes that are part of the same package.
24. Explain the difference between composition (i.e., the has-a relationship) and inheritance (i.e., the is-a rela-tionship).
With inheritance, a class inherits attributes and behaviors from another class. All objects of the new class can betreated as their own type and as their direct and indirect superclass types. With composition, a new class is com-
posed of objects of existing classes. In this relationship, the new class normally cannot be treated as an object of any of its component classes.
25. When an object of a subclass is created, the constructor for that subclass object is invoked to initialize thesubclass object. Explain the complete details of initializing an object of class BasePlusCommissionEmployee with six arguments. Assume the CommissionEmployee -BasePlusCommissionEmployee hierarchy discussed inthis chapter.
When a program creates aBasePlusCommissionEmployee object, the BasePlusCommissionEmployee constructoris called. That constructor calls CommissionEmployee ’s constructor, which in turn calls Object’s constructor.Class Object’s constructor has an empty body, so it immediately returns control to CommissionEmployee ’s con-structor, which then sets the values of the first name, last name, social security number, gross sales and commis-sion rate. When CommissionEmployee ’s constructor completes execution, it returns control to
BasePlusCommissionEmployee ’s constructor, which sets the base salary.
26. Explain how to invoke a superclass method from a subclass method for the case in which the subclass methodoverrides a superclass method and the case in which the subclass method does not override a superclassmethod.
In the case where the subclass method overrides the superclass method, it is necessary to explicitly use the key- word super, to invoke the method of the superclass. When the subclass method does not override the superclassmethod, the superclass method can be invoked simply by using its name and appropriate arguments.
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 11/42
Prelab Activities Name:
Correct the Code
Chapter 9 Object-Oriented Programming: Inheritance 11
Name: Date:
Section:
Correct theCode
Determine if there is an error in each of the following program segments. If there is an error, specify whether itis a logic error or a compilation error, circle the error in the program and write the corrected code in the spaceprovided after each problem. If the code does not contain an error, write “no error.” [Note: There may be morethan one error in a program segment.]
For questions 27–29 assume the definitions of classes CommissionEmployee and BasePlusCommissionEmployee inFig. L 9.1 and Fig. L 9.2.
1 // Fig. 9.15: CommissionEmployee.java2 // CommissionEmployee class represents a commission employee.3
4 public class CommissionEmployee5 {6 private String firstName;7 private String lastName;8 private String socialSecurityNumber;9 private double grossSales; // gross weekly sales
10 private double commissionRate; // commission percentage11
12 // five-argument constructor
13 public CommissionEmployee( String first, String last, String ssn,14 double sales, double rate )15 {16 // implicit call to Object constructor occurs here17 firstName = first;18 lastName = last;19 socialSecurityNumber = ssn;20 setGrossSales( sales ); // validate and store gross sales21 setCommissionRate( rate ); // validate and store commission rate22
23 System.out.printf(24 "\nCommissionEmployee constructor:\n%s\n", this );25 } // end five-argument CommissionEmployee constructor26
27 // set first name28 public void setFirstName( String first )29 {30 firstName = first;31 } // end method setFirstName32
33 // return first name34 public String getFirstName()35 {36 return firstName;37 } // end method getFirstName38
Fig. L 9.1 | CommissionEmployee.java. (Part 1 of 3.)
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 12/42
Prelab Activities Name:
Correct the Code
12 Object-Oriented Programming: Inheritance Chapter 9
39 // set last name40 public void setLastName( String last )41 {42 lastName = last;43 } // end method setLastName44
45 // return last name46 public String getLastName()47 {48 return lastName;49 } // end method getLastName50
51 // set social security number52 public void setSocialSecurityNumber( String ssn )53 {54 socialSecurityNumber = ssn; // should validate55 } // end method setSocialSecurityNumber56
57 // return social security number58 public String getSocialSecurityNumber()59 {60 return socialSecurityNumber;61 } // end method getSocialSecurityNumber62
63 // set gross sales amount64 public void setGrossSales( double sales )65 {66 grossSales = ( sales < 0.0 ) ? 0.0 : sales;67 } // end method setGrossSales
6869 // return gross sales amount70 public double getGrossSales()71 {72 return grossSales;73 } // end method getGrossSales74 75 // set commission rate76 public void setCommissionRate( double rate )77 {78 commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;79 } // end method setCommissionRate80
81 // return commission rate82 public double getCommissionRate()
83 {84 return commissionRate;85 } // end method getCommissionRate86
87 // calculate earnings88 public double earnings()89 {90 return getCommissionRate() * getGrossSales();91 } // end method earnings92
93 // return String representation of CommissionEmployee object94 public String toString()95 {
Fig. L 9.1 | CommissionEmployee.java. (Part 2 of 3.)
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 13/42
Prelab Activities Name:
Correct the Code
Chapter 9 Object-Oriented Programming: Inheritance 13
96 return String.format( "%s: %s %s\n%s: %s\n%s: %.2f\n%s: %.2f",97 "commission employee", getFirstName(), getLastName(),98 "social security number", getSocialSecurityNumber(),99 "gross sales", getGrossSales(),100 "commission rate", getCommissionRate() );101 } // end method toString102 } // end class CommissionEmployee
1 // Fig. 9.16: BasePlusCommissionEmployee.java2 // BasePlusCommissionEmployee class declaration.3
4 public class BasePlusCommissionEmployee extends CommissionEmployee5 {6 private double baseSalary; // base salary per week7
8 // six-argument constructor9 public BasePlusCommissionEmployee( String first, String last,
10 String ssn, double sales, double rate, double salary )11 {12 // implicit call to CommissionEmployee constructor occurs here13 } // end six-argument BasePlusCommissionEmployee constructor14 15 // set base salary16 public void setBaseSalary( double salary )17 {18 baseSalary = ( salary < 0.0 ) ? 0.0 : salary;
19 } // end method setBaseSalary20
21 // return base salary22 public double getBaseSalary()23 {24 return baseSalary;25 } // end method getBaseSalary26
27 // calculate earnings28 public double earnings()29 {30 return getBaseSalary() + super.earnings();31 } // end method earnings32 } // end class BasePlusCommissionEmployee
Fig. L 9.2 | BasePlusCommissionEmployee.java
Fig. L 9.1 | CommissionEmployee.java. (Part 3 of 3.)
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 14/42
Prelab Activities Name:
Correct the Code
14 Object-Oriented Programming: Inheritance Chapter 9
27. The following constructor, when inserted into class BasePlusCommissionEmployee , should invoke a Com-
missionEmployee constructor to initialize the CommissionEmployee part of a BasePlusCommissionEmploy-
ee object.
Your answer:
• Line 5, missing parameter to CommissionEmployee constructor. Compilation error.
28. The following toString method, when inserted into class BasePlusCommissionEmployee , should return a string consisting of CommissionEmployee ’s output string along with the base salary of this object.
Your answer:
• Method toString calls itself. Must use super to invoke the superclass toString method. Logic error.
1 // constructor2 public BasePlusCommissionEmployee( String first, String last,3 String ssn, double sales, double rate, double salary )4 {5 super( first, last, ssn, sales );6 setBaseSalary( salary ); // validate and store base salary7 }
1 // constructor2 public BasePlusCommissionEmployee( String first, String last,3 String ssn, double sales, double rate, double salary )4 {5 super( first, last, ssn, sales );6 setBaseSalary( salary ); // validate and store base salary7 }
1 // return String representation of BasePlusCommissionEmployee2 public String toString()3 {4 return String.format( "%s %s\n%s: %.2f", "base-salaried",5 toString(), "base salary", getBaseSalary() );6 }
1 // return String representation of BasePlusCommissionEmployee
2 public String toString()3 {4 return String.format( "%s %s\n%s: %.2f", "base-salaried",5 toString(), "base salary", getBaseSalary() );6 }
, rate
super.
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 15/42
Prelab Activities Name:
Correct the Code
Chapter 9 Object-Oriented Programming: Inheritance 15
29. The following earnings method, when inserted into class BasePlusCommissionEmployee , should use Com-
missionEmployee ’s earnings method to help calculate the earnings for this object.
Your answer:
• Method earnings calls itself. Must use super to invoke the superclass earnings method. Logic error.
1 // calculate earnings2 public double earnings()3 {4 return getBaseSalary() + earnings();5 } // end method earnings
1 // calculate earnings2 public double earnings()3 {4 return getBaseSalary() + earnings();5 } // end method earnings
super.
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 17/42
Chapter 9 Object-Oriented Programming: Inheritance 17
Lab Exercise
Name: Date:
Section:
Lab Exercise 1 — Employee Hierarchy
This problem is intended to be solved in a closed-lab session with a teaching assistant or instructor present. Theproblem is divided into six parts:
1. Lab Objectives
2. Description of the Problem
3. Sample Output
4. Program Template (Fig. L 9.3)
5. Problem-Solving Tips6. Follow-Up Question and Activity
The program template represents a complete working Java program, with one or more key lines of code replaced with comments. Read the problem description and examine the sample output; then study the template code.Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute theprogram. Compare your output with the sample output provided. Then answer the follow-up question. Thesource code for the template is available at www.pearsonhighered.com/deitel .
Lab ObjectivesThis lab was designed to reinforce programming concepts from Chapter 9 of Java How to Program: 8/e . In thislab, you will practice:
• Using a has-a relationship.
The follow-up question and activity also will give you practice:
• Comparing the is-a relationship to the has-a relationship.
Description of the ProblemMany programs written with inheritance could be written with composition instead, and vice versa. Rewrite classBasePlusCommissionEmployee of the CommissionEmployee–BasePlusCommissionEmployee hierarchy (Section9.4.5) to use composition rather than inheritance.
Template
1 // Exercise 9.3 solution: BasePlusCommissionEmployee.java2 // BasePlusCommissionEmployee using composition.
34 public class BasePlusCommissionEmployee5 {6 /* declare instance variable to satisfy the has-a relationship */7 private double baseSalary; // base salary per week8
9 // six-argument constructor10 public BasePlusCommissionEmployee( String first, String last,11 String ssn, double sales, double rate, double salary )12 {13 /* construct the CommissionEmployee portion of this object */14 setBaseSalary( salary ); // validate and store base salary15 } // end six-argument BasePlusCommissionEmployee constructor
Fig. L 9.3 | BasePlusCommissionEmployee.java. (Part 1 of 3.)
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 18/42
Lab Exercise Name:
Lab Exercise 1 — Employee Hierarchy
18 Object-Oriented Programming: Inheritance Chapter 9
16 17 // set first name18 public void setFirstName( String first )19 {20 /* set the first name of the composed CommissionEmployee object */21 } // end method setFirstName22
23 // return first name24 public String getFirstName()25 {26 /* return the first name of the composed CommissionEmployee object */27 } // end method getFirstName28
29 // set last name30 public void setLastName( String last )31 {32 /* set the last name of the composed CommissionEmployee object */33 } // end method setLastName34
35 // return last name36 public String getLastName()37 {38 /* return the last name of the composed CommissionEmployee object */39 } // end method getLastName40
41 // set social security number42 public void setSocialSecurityNumber( String ssn )43 {44 /* set the social security number of the composed CommissionEmployee object */
45 } // end method setSocialSecurityNumber46
47 // return social security number48 public String getSocialSecurityNumber()49 {50 /* return the social security number of the composed CommissionEmployee51 object */52 } // end method getSocialSecurityNumber53
54 // set commission employee's gross sales amount55 public void setGrossSales( double sales )56 {57 /* set the gross sales of the composed CommissionEmployee object */58 } // end method setGrossSales59
60 // return commission employee's gross sales amount61 public double getGrossSales()62 {63 /* return the gross sales of the composed CommissionEmployee object */64 } // end method getGrossSales65 66 // set commission employee's rate67 public void setCommissionRate( double rate )68 {69 /* Set the commission rate of the composed CommissionEmployee object */70 } // end method setCommissionRate71
Fig. L 9.3 | BasePlusCommissionEmployee.java . (Part 2 of 3.)
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 19/42
Lab Exercise Name:
Lab Exercise 1 — Employee Hierarchy
Chapter 9 Object-Oriented Programming: Inheritance 19
Problem-Solving Tips
1. Look at the CommissionEmployee class to determine which functionality to use in each of the Base-
PlusCommissionEmployee class’s constructor and methods.
2. If you have any questions as you proceed, ask your lab instructor for assistance.
Solution
72 // return commission employee's rate73 public double getCommissionRate()74 {75 /* Return the commission rate of the composed CommissionEmployee object */76 } // end method getCommissionRate77
78 // set base-salaried commission employee's base salary79 public void setBaseSalary( double salary )80 {81 baseSalary = ( salary < 0.0 ) ? 0.0 : salary;82 } // end method setBaseSalary83
84 // return base-salaried commission employee's base salary85 public double getBaseSalary()86 {87 return baseSalary;88 } // end method getBaseSalary89
90 // calculate base-salaried commission employee's earnings91 public double earnings()92 {93 /* Calculate the earnings of this object using the earnings of the composed94 CommissionEmployee object */95 } // end method earnings96
97 // return String representation of BasePlusCommissionEmployee98 public String toString()99 {100 /* Return a string consisting of the string representation of the composed
101 CommissionEmployee object along with the base salary */102 } // end method toString103 } // end class BasePlusCommissionEmployee
1 // Exercise 9.3 solution: BasePlusCommissionEmployee.java2 // BasePlusCommissionEmployee using composition.3
4 public class BasePlusCommissionEmployee5 {6 private CommissionEmployee commissionEmployee; // composition7 private double baseSalary; // base salary per week8
9 // six-argument constructor10 public BasePlusCommissionEmployee( String first, String last,11 String ssn, double sales, double rate, double salary )12 {
Fig. L 9.3 | BasePlusCommissionEmployee.java. (Part 3 of 3.)
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 20/42
Lab Exercise Name:
Lab Exercise 1 — Employee Hierarchy
20 Object-Oriented Programming: Inheritance Chapter 9
13 commissionEmployee =14 new CommissionEmployee( first, last, ssn, sales, rate );15 setBaseSalary( salary ); // validate and store base salary16 } // end six-argument BasePlusCommissionEmployee constructor17 18 // set first name19 public void setFirstName( String first )20 {21 commissionEmployee.setFirstName( first );22 } // end method setFirstName23
24 // return first name25 public String getFirstName()26 {27 return commissionEmployee.getFirstName();28 } // end method getFirstName29
30 // set last name31 public void setLastName( String last )32 {33 commissionEmployee.setLastName( last );34 } // end method setLastName35
36 // return last name37 public String getLastName()38 {39 return commissionEmployee.getLastName();40 } // end method getLastName41
42 // set social security number43 public void setSocialSecurityNumber( String ssn )44 {45 commissionEmployee.setSocialSecurityNumber( ssn );46 } // end method setSocialSecurityNumber47
48 // return social security number49 public String getSocialSecurityNumber()50 {51 return commissionEmployee.getSocialSecurityNumber();52 } // end method getSocialSecurityNumber53
54 // set commission employee's gross sales amount55 public void setGrossSales( double sales )56 {
57 commissionEmployee.setGrossSales( sales );58 } // end method setGrossSales59
60 // return commission employee's gross sales amount61 public double getGrossSales()62 {63 return commissionEmployee.getGrossSales();64 } // end method getGrossSales65 66 // set commission employee's rate67 public void setCommissionRate( double rate )68 {69 commissionEmployee.setCommissionRate( rate );70 } // end method setCommissionRate
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 21/42
Lab Exercise Name:
Lab Exercise 1 — Employee Hierarchy
Chapter 9 Object-Oriented Programming: Inheritance 21
Follow-Up Question and Activity
1. Assess the relative merits of the two approaches for theCommissionEmployee and BasePlusCommission-
Employee problems, as well as for object-oriented programs in general. Which approach is more natural? Why?
For a relatively short program like this one, either approach is acceptable. But as programs become larger with more and more objects being instantiated, inheritance becomes preferable because it makes the programeasier to modify and promotes the reuse of code. The inheritance approach is more natural because a base-salariedcommission employee is a commission employee. Composition is defined by the has-a relationship, and clearly
it would be strange to say that “a base-salaried commission employee has a commission employee.”
71
72 // return commission employee's rate73 public double getCommissionRate()74 {75 return commissionEmployee.getCommissionRate();76 } // end method getCommissionRate77
78 // set base-salaried commission employee's base salary79 public void setBaseSalary( double salary )80 {81 baseSalary = ( salary < 0.0 ) ? 0.0 : salary;82 } // end method setBaseSalary83
84 // return base-salaried commission employee's base salary85 public double getBaseSalary()86 {87 return baseSalary;88 } // end method getBaseSalary89
90 // calculate base-salaried commission employee's earnings91 public double earnings()92 {93 return getBaseSalary() + commissionEmployee.earnings();94 } // end method earnings95
96 // return String representation of BasePlusCommissionEmployee97 public String toString()98 {99 return String.format( "%s %s\n%s: %.2f", "base-salaried",
100 commissionEmployee.toString(), "base salary", getBaseSalary() );101 } // end method toString102 } // end class BasePlusCommissionEmployee
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 23/42
Chapter 9 Object-Oriented Programming: Inheritance 23
Postlab Activities
Name: Date:
Section:
Coding Exercises
These coding exercises reinforce the lessons learned in the lab and provide additional programming experienceoutside the classroom and laboratory environment. They serve as a review after you have successfully completedthe Prelab Activities and Lab Exercises .
For each of the following problems, write a program or a program segment that performs the specified action.
1. Declare the headers for the classes in the class diagram of Fig. L 9.4.
Fig. L 9.4 | Inheritance hierarchy for Shapes.
1 // Exercise 9.6 Solution: Shape.java2 // Definition of class Shape.3
4 public abstract class Shape5 {6 private int x, y; // coordinates of shape7
8 // constructor9 public Shape( int x, int y )
10 {11 this.x = x;12 this.y = y;13 }
1415 // set x coordinate16 public void setX( int x )17 {18 this.x = x;19 }20
21 // set y coordinate22 public void setY( int y )23 {24 this.y = y;25 }26
ThreeDimensionalShape
CubeSphereSquareCircle
Shape
TwoDimensionalShape
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 25/42
Postlab Activities Name:
Coding Exercises
Chapter 9 Object-Oriented Programming: Inheritance 25
1 // Exercise 9.6 Solution: ThreeDimensionalShape.java2 // Defition of class ThreeDimensionalShape3
4 public abstract class ThreeDimensionalShape extends Shape5 {6 private double dimension1, dimension2, dimension3;7
8 // constructor9 public ThreeDimensionalShape( int x, int y, double d1, double d2, double d3 )
10 {11 super( x, y );12 dimension1 = d1;13 dimension2 = d2;14 dimension3 = d3;15 }16
17 // set methods18 public void setDimension1( double d )19 {20 dimension1 = d;21 }22
23 public void setDimension2( double d )24 {25 dimension2 = d;26 }27
28 public void setDimension3( double d )29 {
30 dimension3 = d;31 }32
33 // get methods34 public double getDimension1()35 {36 return dimension1;37 }38
39 public double getDimension2()40 {41 return dimension2;42 }43
44 public double getDimension3()
45 {46 return dimension3;47 }48
49 // abstract methods50 public abstract double area();51 public abstract double volume();52 } // end class ThreeDimensionalShape
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 26/42
Postlab Activities Name:
Coding Exercises
26 Object-Oriented Programming: Inheritance Chapter 9
1 // Exercise 9.6 Solution: Circle.java2 // Definition of class Circle.3
4 public class Circle extends TwoDimensionalShape5 {6 // constructor7 public Circle( int x, int y, double radius )8 {9 super( x, y, radius, radius );
10 }11
12 // overridden methods13 public String getName()14 {15 return "Circle";16 }17
18 public double area()19 {20 return Math.PI * super.getDimension1() * super.getDimension1();21 }22
23 // set method24 public void setRadius( double radius )25 {26 super.setDimension1( radius );27 }28
29 // get method
30 public double getRadius()31 {32 return super.getDimension1();33 }34 } // end class Circle
1 // Exercise 9.6 Solution: Square.java2 // Definition of class Square.3
4 public class Square extends TwoDimensionalShape5 {6 // constructor7 public Square( int x, int y, double side )8 {
9 super( x, y, side, side );10 }11
12 // overridden methods13 public String getName()14 {15 return "Square";16 }17
18 public double area()19 {20 return super.getDimension1() * super.getDimension1();21 }22
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 27/42
Postlab Activities Name:
Coding Exercises
Chapter 9 Object-Oriented Programming: Inheritance 27
23 // set method24 public void setSide( double side )25 {26 super.setDimension1( side );27 }28
29 // get method30 public double getSide()31 {32 return super.getDimension1();33 }34 } // end class Square
1 // Exercise 9.6 Solution: Sphere.java2 // Definition of class Sphere.3
4 public class Sphere extends ThreeDimensionalShape5 {6 // constructor7 public Sphere( int x, int y, double radius )8 {9 super( x, y, radius, radius, radius );
10 }11
12 // overridden methods13 public String getName()14 {15 return "Sphere";16 }17
18 public double area()19 {20 return 4 * Math.PI * super.getDimension1() * super.getDimension1();21 }22
23 public double volume()24 {25 return 4.0 / 3.0 * Math.PI * super.getDimension1() *26 super.getDimension1() * super.getDimension1();27 }28
29 // set method30 public void setRadius( double radius )
31 {32 super.setDimension1( radius );33 }34
35 // get method36 public double getRadius()37 {38 return super.getDimension1();39 }40 } // end class Sphere
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 28/42
Postlab Activities Name:
Coding Exercises
28 Object-Oriented Programming: Inheritance Chapter 9
2. Declare toString methods for all the classes in Coding Exercise 1. Class Shape’s toString method should
return the string "Shape". The toString method of each of the subclasses in the hierarchy should return a string containing the class’s name, the string " is a " and the result of a call to the superclass’s toStringmethod.
1 // Exercise 9.6 Solution: Cube.java2 // Definition of class Cube.3
4 public class Cube extends ThreeDimensionalShape5 {6 // constructor7 public Cube( int x, int y, double side )8 {9 super( x, y, side, side, side );
10 }11
12 // overridden methods13 public String getName()14 {15 return "Cube";16 }17
18 public double area()19 {20 return 6 * super.getDimension1() * super.getDimension1();21 }22
23 public double volume()24 {25 return super.getDimension1() * super.getDimension1() * super.getDimension1();26 }27
28 // set method29 public void setSide( double side )
30 {31 super.setDimension1( side );32 }33
34 // get method35 public double getSide()36 {37 return super.getDimension1();38 }39 } // end class Cube
1 // Exercise 9.6 Solution: Shape.java2 // Definition of class Shape.3
4 public abstract class Shape5 {6 private int x, y; // coordinates of shape7
8 // constructor9 public Shape( int x, int y )
10 {
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 29/42
Postlab Activities Name:
Coding Exercises
Chapter 9 Object-Oriented Programming: Inheritance 29
11 this.x = x;12 this.y = y;13 }14
15 // set x coordinate16 public void setX( int x )17 {18 this.x = x;19 }20
21 // set y coordinate22 public void setY( int y )23 {24 this.y = y;25 }26
27 // get x coordinate28 public int getX()29 {30 return x;31 }32
33 // get y coordinate34 public int getY()35 {36 return y;37 }38
39 // abstract methods
40 public abstract String getName();41
42 public String toString()43 {44 return "Shape";45 }46 } // end class Shape
1 // Exercise 9.6 Solution: TwoDimensionalShape.java2 // Definition of class TwoDimensionalShape.3
4 public abstract class TwoDimensionalShape extends Shape5 {6 private double dimension1, dimension2;
7
8 // constructor9 public TwoDimensionalShape( int x, int y, double d1, double d2 )
10 {11 super( x, y );12 dimension1 = d1;13 dimension2 = d2;14 }15
16 // set methods17 public void setDimension1( double d )18 {19 dimension1 = d;20 }
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 30/42
Postlab Activities Name:
Coding Exercises
30 Object-Oriented Programming: Inheritance Chapter 9
21
22 public void setDimension2( double d )23 {24 dimension2 = d;25 }26
27 // get methods28 public double getDimension1()29 {30 return dimension1;31 }32
33 public double getDimension2()34 {35 return dimension2;36 }37
38 // abstract method39 public abstract double area();40
41 public String toString()42 {43 return String.format( "TwoDimensionalShape is a %s", super.toString() );44 }45 } // end class TwoDimensionalShape
1 // Exercise 9.6 Solution: ThreeDimensionalShape.java2 // Defition of class ThreeDimensionalShape3
4 public abstract class ThreeDimensionalShape extends Shape5 {6 private double dimension1, dimension2, dimension3;7
8 // constructor9 public ThreeDimensionalShape( int x, int y, double d1, double d2, double d3 )
10 {11 super( x, y );12 dimension1 = d1;13 dimension2 = d2;14 dimension3 = d3;15 }16
17 // set methods
18 public void setDimension1( double d )19 {20 dimension1 = d;21 }22
23 public void setDimension2( double d )24 {25 dimension2 = d;26 }27
28 public void setDimension3( double d )29 {30 dimension3 = d;31 }
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 31/42
Postlab Activities Name:
Coding Exercises
Chapter 9 Object-Oriented Programming: Inheritance 31
32
33 // get methods34 public double getDimension1()35 {36 return dimension1;37 }38
39 public double getDimension2()40 {41 return dimension2;42 }43
44 public double getDimension3()45 {46 return dimension3;47 }48
49 // abstract methods50 public abstract double area();51 public abstract double volume();52
53 public String toString()54 {55 return String.format( "ThreeDimensionalShape is a %s", super.toString() );56 }57 } // end class ThreeDimensionalShape
1 // Exercise 9.6 Solution: Circle.java2 // Definition of class Circle.3
4 public class Circle extends TwoDimensionalShape5 {6 // constructor7 public Circle( int x, int y, double radius )8 {9 super( x, y, radius, radius );
10 }11
12 // overridden methods13 public String getName()14 {15 return "Circle";16 }
17
18 public double area()19 {20 return Math.PI * super.getDimension1() * super.getDimension1();21 }22
23 // set method24 public void setRadius( double radius )25 {26 super.setDimension1( radius );27 }28
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 32/42
Postlab Activities Name:
Coding Exercises
32 Object-Oriented Programming: Inheritance Chapter 9
29 // get method30 public double getRadius()31 {32 return super.getDimension1();33 }34
35 public String toString()36 {37 return String.format( "Circle is a %s", super.toString() );38 }39 } // end class Circle
1 // Exercise 9.6 Solution: Square.java2 // Definition of class Square.3
4 public class Square extends TwoDimensionalShape5 {6 // constructor7 public Square( int x, int y, double side )8 {9 super( x, y, side, side );
10 }11
12 // overridden methods13 public String getName()14 {15 return "Square";16 }17
18 public double area()19 {20 return super.getDimension1() * super.getDimension1();21 }22
23 // set method24 public void setSide( double side )25 {26 super.setDimension1( side );27 }28
29 // get method30 public double getSide()31 {
32 return super.getDimension1();33 }34
35 public String toString()36 {37 return String.format( "Square is a %s", super.toString() );38 }39 } // end class Square
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 33/42
Postlab Activities Name:
Coding Exercises
Chapter 9 Object-Oriented Programming: Inheritance 33
1 // Exercise 9.6 Solution: Sphere.java2 // Definition of class Sphere.3
4 public class Sphere extends ThreeDimensionalShape5 {6 // constructor7 public Sphere( int x, int y, double radius )8 {9 super( x, y, radius, radius, radius );
10 }11
12 // overridden methods13 public String getName()14 {15 return "Sphere";16 }17
18 public double area()19 {20 return 4 * Math.PI * super.getDimension1() * super.getDimension1();21 }22
23 public double volume()24 {25 return 4.0 / 3.0 * Math.PI * super.getDimension1() *26 super.getDimension1() * super.getDimension1();27 }28
29 // set method
30 public void setRadius( double radius )31 {32 super.setDimension1( radius );33 }34
35 // get method36 public double getRadius()37 {38 return super.getDimension1();39 }40
41 public String toString()42 {43 return String.format( "Sphere is a %s", super.toString() );44 }
45 } // end class Sphere
1 // Exercise 9.6 Solution: Cube.java2 // Definition of class Cube.3
4 public class Cube extends ThreeDimensionalShape5 {6 // constructor7 public Cube( int x, int y, double side )8 {9 super( x, y, side, side, side );
10 }
Fig. L 9.5 | Cube.java (Part 1 of 2.)
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 34/42
Postlab Activities Name:
Coding Exercises
34 Object-Oriented Programming: Inheritance Chapter 9
3. Write an application that creates one object of each of the classes Circle, Square, Sphere and Cube, andinvokes their toString methods. The output for each object should show the is-a relationships between thatobject’s class and its superclasses.
11
12 // overridden methods13 public String getName()14 {15 return "Cube";16 }17
18 public double area()19 {20 return 6 * super.getDimension1() * super.getDimension1();21 }22
23 public double volume()24 {25 return super.getDimension1() * super.getDimension1() * super.getDimension1();26 }27
28 // set method29 public void setSide( double side )30 {31 super.setDimension1( side );32 }33
34 // get method35 public double getSide()36 {37 return super.getDimension1();38 }39
40 public String toString()41 {42 return String.format( "Cube is a %s", super.toString() );43 }44 } // end class Cube
1 // Exercise 9.8 Solution: ShapeTest.java2 // Program tests the Shape hierarchy.3
4 public class ShapeTest5 {6 private Shape shapeArray[];7
8 // create shapes9 public ShapeTest()
10 {11 shapeArray = new Shape[ 4 ];12
13 shapeArray[ 0 ] = new Circle( 22, 88, 1.25 );14 shapeArray[ 1 ] = new Square( 71, 96, 2.5 );
Fig. L 9.5 | Cube.java (Part 2 of 2.)
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 35/42
Postlab Activities Name:
Coding Exercises
Chapter 9 Object-Oriented Programming: Inheritance 35
15 shapeArray[ 2 ] = new Sphere( 8, 89, 3.75 );16 shapeArray[ 3 ] = new Cube( 79, 61, 5.0 );17 } // end ShapeTest constructor18
19 // display shape info20 public void displayShapeInfo()21 {22 // call method toString on all shapes23 for ( int i = 0; i < shapeArray.length; i++ )24 {25 System.out.printf( "%s: %s\n", shapeArray[ i ].getName(), shapeArray[ i ] );26
27 if ( shapeArray[ i ] instanceof TwoDimensionalShape )28 {29 TwoDimensionalShape current = ( TwoDimensionalShape ) shapeArray[ i ];30 System.out.printf( "%s's area is %.2f\n", current.getName(),31 current.area() );32 } // end if33
34 if ( shapeArray[ i ] instanceof ThreeDimensionalShape )35 {36 ThreeDimensionalShape current = ( ThreeDimensionalShape ) shapeArray[ i ];37
38 System.out.printf( "%s's area is %.2f\n%s's volume is %.2f\n",39 current.getName(), current.area(), current.getName(),40 current.volume() );41 } // end if42 } // end for43 } // end method displayShapeInfo
4445 // create ShapeTest object and display info46 public static void main( String args[] )47 {48 ShapeTest driver = new ShapeTest();49 driver.displayShapeInfo();50 } // end main51 } // end class ShapeTest
Circle: Circle is a TwoDimensionalShape is a ShapeCircle's area is 4.91Square: Square is a TwoDimensionalShape is a ShapeSquare's area is 6.25Sphere: Sphere is a ThreeDimensionalShape is a ShapeSphere's area is 176.71
Sphere's volume is 220.89Cube: Cube is a ThreeDimensionalShape is a ShapeCube's area is 150.00Cube's volume is 125.00
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 37/42
Postlab Activities Name:
Programming Challenges
Chapter 9 Object-Oriented Programming: Inheritance 37
Name: Date:
Section:
Programming Challenges
The Programming Challenges are more involved than the Coding Exercises and may require a significant amountof time to complete. Write a Java program for each of the problems in this section. The answers to these problemsare available at www.pearsonhighered.com/deitel . Pseudocode, hints or sample outputs are provided for eachproblem to aid you in your programming.
1. Write an inheritance hierarchy for classes Quadrilateral, Trapezoid, Parallelogram, Rectangle andSquare. Use Quadrilateral as the superclass of the hierarchy. Specify the instance variables and methodsfor each class. The private instance variables of Quadrilateral should be the x - y coordinate pairs for thefour endpoints of the Quadrilateral. Write a program that instantiates objects of your classes and outputseach object’s area (except Quadrilateral).
Hints:
• Create and use a Point class to represent the corners of the shapes.
• Your output should appear as follows:
Coordinates of Quadrilateral are:( 1.1, 1.2 ), ( 6.6, 2.8 ), ( 6.2, 9.9 ), ( 2.2, 7.4 )
Coordinates of Trapezoid are:( 0.0, 0.0 ), ( 10.0, 0.0 ), ( 8.0, 5.0 ), ( 3.3, 5.0 )Height is: 5.0Area is: 36.75
Coordinates of Parallelogram are:( 5.0, 5.0 ), ( 11.0, 5.0 ), ( 12.0, 20.0 ), ( 6.0, 20.0 )Width is: 6.0Height is: 15.0Area is: 90.0
Coordinates of Rectangle are:( 17.0, 14.0 ), ( 30.0, 14.0 ), ( 30.0, 28.0 ), ( 17.0, 28.0 )Width is: 13.0Height is: 14.0Area is: 182.0
Coordinates of Square are:( 4.0, 0.0 ), ( 8.0, 0.0 ), ( 8.0, 4.0 ), ( 4.0, 4.0 )Side is: 4.0Area is: 16.0
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 38/42
Postlab Activities Name:
Programming Challenges
38 Object-Oriented Programming: Inheritance Chapter 9
Solution
1 // Exercise 9.8 Solution: QuadrilateralTest.java2 // Driver for Exercise 9.83
4 public class QuadrilateralTest5 {6 public static void main( String args[] )7 {8 // NOTE: All coordinates are assumed to form the proper shapes9 // A quadrilateral is a four-sided polygon
10 Quadrilateral quadrilateral = new Quadrilateral( new Point( 1.1, 1.2 ),11 new Point( 6.6, 2.8 ), new Point( 6.2, 9.9 ), new Point( 2.2, 7.4 ) );
1213 // A trapezoid is a quadrilateral having exactly two parallel sides14 Trapezoid trapezoid = new Trapezoid( new Point( 0.0, 0.0 ),15 new Point( 10.0, 0.0 ), new Point( 8.0, 5.0 ), new Point( 3.3, 5.0 ) );16 17 // A parallelogram is a quadrilateral with opposite sides parallel18 Parallelogram parallelogram = new Parallelogram( new Point( 5.0, 5.0 ),19 new Point( 11.0, 5.0 ), new Point( 12.0, 20.0 ), new Point( 6.0, 20.0 ) );20
21 // A rectangle is an equiangular parallelogram22 Rectangle rectangle = new Rectangle( new Point( 17.0, 14.0 ),23 new Point( 30.0, 14.0 ), new Point( 30.0, 28.0 ), new Point( 17.0, 28.0 ) );24
25 // A square is an equiangular and equilateral parallelogram26 Square square = new Square( new Point( 4.0, 0.0 ),27 new Point( 8.0, 0.0 ), new Point( 8.0, 4.0 ), new Point( 4.0, 4.0 ) );28
29 System.out.printf(30 "%s %s %s %s %s\n", quadrilateral, trapezoid, parallelogram,31 rectangle, square );32 } // end main33 } // end class QuadrilateralTest
1 // Exercise 9.8 solution: Point.java2 // Class Point definition3
4 public class Point5 {6 private double x; // x coordinate7
private double y; // y coordinate8 9 // two-argument constructor
10 public Point( double xCoordinate, double yCoordinate )11 {12 x = xCoordinate; // set x13 y = yCoordinate; // set y14 } // end two-argument Point constructor15
16 // return x17 public double getX()18 {19 return x;20 } // end method getX
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 39/42
Postlab Activities Name:
Programming Challenges
Chapter 9 Object-Oriented Programming: Inheritance 39
21 22 // return y23 public double getY()24 {25 return y;26 } // end method getY27
28 // return string representation of Point object29 public String toString()30 {31 return String.format( "( %.1f, %.1f )", getX(), getY() );32 } // end method toString33 } // end class Point
1 // Exercise 9.8 solution: Quadrilateral.java2 // Class Quadrilateral definition3
4 public class Quadrilateral5 {6 private Point point1; // first endpoint7 private Point point2; // second endpoint8 private Point point3; // third endpoint9 private Point point4; // fourth endpoint
10
11 // eight-argument constructor12 public Quadrilateral( Point first, Point second, Point third, Point fourth )13 {14 point1 = first;15 point2 = second;16 point3 = third;17 point4 = fourth;18 } // end eight-argument Quadrilateral constructor19
20 // return point121 public Point getPoint1()22 {23 return point1;24 } // end method getPoint125
26 // return point227 public Point getPoint2()28 {29 return point2;
30 } // end method getPoint231
32 // return point333 public Point getPoint3()34 {35 return point3;36 } // end method getPoint337
38 // return point439 public Point getPoint4()40 {41 return point4;42 } // end method getPoint443
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 40/42
Postlab Activities Name:
Programming Challenges
40 Object-Oriented Programming: Inheritance Chapter 9
44 // return string representation of a Quadrilateral object45 public String toString()46 {47 return String.format( "%s:\n%s",48 "Coordinates of Quadrilateral are", getCoordinatesAsString() );49 } // end method toString50
51 // return string containing coordinates as strings52 public String getCoordinatesAsString()53 {54 return String.format(55 "%s, %s, %s, %s\n", point1, point2, point3, point4 );56 } // end method getCoordinatesAsString57 } // end class Quadrilateral
1 // Exercise 9.8 solution: Trapezoid.java2 // Class Trapezoid definition3
4 public class Trapezoid extends Quadrilateral5 {6 private double height; // height of trapezoid7
8 // eight-argument constructor9 public Trapezoid( Point first, Point second, Point third, Point fourth )
10 {11 super( first, second, third, fourth );12 } // end of eight-argument Trapezoid constructor 13
14 // return height15 public double getHeight()16 {17 if ( getPoint1().getY() == getPoint2().getY() )18 return Math.abs( getPoint2().getY() - getPoint3().getY() );19 else20 return Math.abs( getPoint1().getY() - getPoint2().getY() );21 } // end method getHeight22
23 // return area24 public double getArea()25 {26 return getSumOfTwoSides() * getHeight() / 2.0;27 } // end method getArea28
29 // return the sum of the trapezoid's two sides30 public double getSumOfTwoSides()31 {32 if ( getPoint1().getY() == getPoint2().getY() )33 return Math.abs( getPoint1().getX() - getPoint2().getX() ) +34 Math.abs( getPoint3().getX() - getPoint4().getX() );35 else36 return Math.abs( getPoint2().getX() - getPoint3().getX() ) +37 Math.abs( getPoint4().getX() - getPoint1().getX() );38 } // end method getSumOfTwoSides39
40 // return string representation of Trapezoid object41 public String toString()42 {
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 41/42
Postlab Activities Name:
Programming Challenges
Chapter 9 Object-Oriented Programming: Inheritance 41
43 return String.format( "\n%s:\n%s%s: %s\n%s: %s\n",44 "Coordinates of Trapezoid are", getCoordinatesAsString(),45 "Height is", getHeight(), "Area is", getArea() );46 } // end method toString47 } // end class Trapezoid
1 // Exercise 9.8 solution: Parallelogram.java2 // Class Parallelogram definition3
4 public class Parallelogram extends Trapezoid5 {6 // eight-argument constructor7
public Parallelogram( Point first, Point second, Point third, Point fourth )8 {9 super( first, second, third, fourth );
10 } // end eight-argument Parallelogram constructor11
12 // return width of parallelogram13 public double getWidth()14 {15 if ( getPoint1().getY() == getPoint2().getY() )16 return Math.abs( getPoint1().getX() - getPoint2().getX() );17 else18 return Math.abs( getPoint2().getX() - getPoint3().getX() );19 } // end method getWidth20
21 // return string representation of Parallelogram object22 public String toString()23 {24 return String.format( "\n%s:\n%s%s: %s\n%s: %s\n%s: %s\n",25 "Coordinates of Parallelogram are", getCoordinatesAsString(),26 "Width is", getWidth(), "Height is", getHeight(),27 "Area is", getArea() );28 } // end method toString29 } // end class Parallelogram
1 // Exercise 9.8 solution: Rectangle.java2 // Class Rectangle definition3
4 public class Rectangle extends Parallelogram5 {6 // eight-argument constructor
7 public Rectangle( Point first, Point second, Point third, Point fourth )8 {9 super( first, second, third, fourth );
10 } // end eight-argument Rectangle constructor11
12 // return string representation of Rectangle object13 public String toString()14 {15 return String.format( "\n%s:\n%s%s: %s\n%s: %s\n%s: %s\n",16 "Coordinates of Rectangle are", getCoordinatesAsString(),17 "Width is", getWidth(), "Height is", getHeight(),18 "Area is", getArea() );19 } // end method toString20 } // end class Rectangle
8/17/2019 Inheritance Lab Manual
http://slidepdf.com/reader/full/inheritance-lab-manual 42/42
Postlab Activities Name:
Programming Challenges
42 Object-Oriented Programming: Inheritance Chapter 9
1 // Exercise 9.8 solution: Square.java2 // Class Square definition3
4 public class Square extends Parallelogram5 {6 // eight-argument constructor7 public Square( Point first, Point second, Point third, Point fourth )8 {9 super( first, second, third, fourth );
10 } // end eight-argument Square constructor11
12 // return string representation of Square object13 public String toString()14 {15 return String.format( "\n%s:\n%s%s: %s\n%s: %s\n",16 "Coordinates of Square are", getCoordinatesAsString(),17 "Side is", getHeight(), "Area is", getArea() );18 } // end method toString 19 } // end class Square