starting out with java: from control structures through objects 5 th edition by tony gaddis

83
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 10

Upload: hewitt

Post on 04-Jan-2016

50 views

Category:

Documents


1 download

DESCRIPTION

Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 10. Code Listing 10-1 (GradedActivity.java) 1 /** A class that holds a grade for a graded activity. General class that w ill be “extended” later . 3 */ 4 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Starting Out with Java: From Control Structures

through Objects

5th edition

By Tony Gaddis

Source Code: Chapter 10

Page 2: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-1 (GradedActivity.java)1 /**

2 A class that holds a grade for a graded activity. General class that3 will be “extended” later.3 */4

5 public class GradedActivity6 {

7 private double score; // Numeric score- Data Field89 /**10 The setScore method sets the score field.11 @param s The value to store in score.12 */13

14 public void setScore( double s ) // Note: NO CONSTRUCTOR Explicit.15 {

16 score = s;17 }1819 /**20 The getScore method returns the score.21 @return The value stored in the score field.22 */

(Continued)

Page 3: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23

24 public double getScore()25 {

26 return score;

27 }2829 /**30 The getGrade method returns a letter grade31 determined from the score field.32 @return The letter grade.33 */34

35 public char getGrade()36 {37 char letterGrade;3839 if (score >= 90)40 letterGrade = 'A';41 else if (score >= 80)42 letterGrade = 'B';43 else if (score >= 70)44 letterGrade = 'C';

(Continued)

Page 4: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

45 else if (score >= 60)46 letterGrade = 'D';47 else48 letterGrade = 'F';49

50 return letterGrade;

51 }52 }

Page 5: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-2 (GradeDemo.java)1 import javax.swing.JOptionPane;23 /**4 This program demonstrates the GradedActivity5 class. Not a sub class.6 */78 public class GradeDemo9 {

10 public static void main(String[] args)11 {

12 String input; // To hold input

13 double testScore; // A test score14

15 // Create a GradedActivity object.

16 GradedActivity grade = new GradedActivity(); // Invokes What?17

18 // Get a test score.

19 Input = JOptionPane.showInputDialog("Enter " +20 "a numeric test score.");

21 testScore = Double.parseDouble(input);22

(Continued)

Page 6: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23 // Store the score in the grade object.

24 grade.setScore(testScore); // Defined where?25

26 // Display the letter grade for the score.

27 JOptionPane.showMessageDialog(null,28 "The grade for that test is " +

29 grade.getGrade());3031 System.exit(0);32 }33 }

Page 7: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-3 (FinalExam.java)1 /**

2 This class determines the grade for a final exam. A sub class-inherits what?3 Does not inherit?3 */4

5 public class FinalExam extends GradedActivity6 {

7 private int numQuestions; // Number of questions

8 private double pointsEach; // Points for each question

9 private int numMissed; // Questions missed1011 /**

12 The constructor sets the number of questions on the13 exam and the number of questions missed.14 @param questions The number of questions.15 @param missed The number of questions missed.16 */17

18 public FinalExam( int questions, int missed ) // What is executed FIRST?19 {20 double numericScore; // To hold a numeric score21

22 // Set the numQuestions and numMissed fields.(Continued)

Page 8: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23 numQuestions = questions;

24 numMissed = missed;2526 27 28 pointsEach = 100.0 / questions;

29 numericScore = 100.0 - (missed * pointsEach); // 3 IV’s are set.30

31 // Call the inherited setScore method to32 // set the numeric score.

33 setScore( numericScore ); // Invokes what? Defined where? Why? 34 }3536 /**37 The getPointsEach method returns the number of38 points each question is worth.39 @return The value in the pointsEach field.40 */41

42 public double getPointsEach() // Accessor43 {

44 return pointsEach;(Continued)

Page 9: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

45 }4647 /**48 The getNumMissed method returns the number of49 questions missed.50 @return The value in the numMissed field.51 */52

53 public int getNumMissed() // Accessor54 {

55 return numMissed;56 }57 }

Page 10: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-4 (FinalExamDemo.java)1 import javax.swing.JOptionPane;23 /**

4 This program demonstrates the FinalExam class,5 which extends the GradedActivity class.6 */7

8 public class FinalExamDemo9 {

10 public static void main(String[] args)

11 {12 String input; // To hold input13 int questions; // Number of questions14 int missed; // Number of questions missed15

16 // Get the number of questions on the exam.17 input = JOptionPane.showInputDialog("How many " +18 "questions are on the final exam?");

19 questions = Integer.parseInt(input);20

21 // Get the number of questions the student missed.

22 input = JOptionPane.showInputDialog("How many " +(Continued)

Page 11: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23 "questions did the student miss?");

24 missed = Integer.parseInt(input);25

26 // Create a FinalExam object.

27 FinalExam exam = new FinalExam(questions, missed);28

29 // Display the test results.

30 JOptionPane.showMessageDialog(null,

31 "Each question counts " + exam.getPointsEach() + // Defined where?32 " points.\nThe exam score is " +

33 exam.getScore() + "\nThe exam grade is " + // Defined where?34 exam.getGrade());3536 System.exit(0);37 }38 }

Page 12: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-5 (SuperClass1.java)1 public class SuperClass12 {3 /**

4 Constructor5 */6

7 public SuperClass1()8 {

9 System.out.println("This is the " +10 "superclass constructor.");11 }12 }

Page 13: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-6 (SubClass1.java)

1 public class SubClass1 extends SuperClass12 {3 /**

4 Constructor5 */6

7 public SubClass1()8 {

9 System.out.println("This is the " +10 "subclass constructor.");11 }12 }

Page 14: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-7 (ConstructorDemo1.java)1 /**

2 This program demonstrates the order in which

3 superclass and subclass constructors are called.4 */5

6 public class ConstructorDemo17 {

8 public static void main(String[] args)

9 {

10 SubClass1 obj = new SubClass1();11 }12 }

Program Output

This is the superclass constructor.This is the subclass constructor.

Page 15: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-8 (SuperClass2.java)

1 public class SuperClass22 {3 /**

4 Constructor #1 No-ARG5 */6

7 public SuperClass2()8 {

9 System.out.println("This is the superclass " +10 "no-arg constructor.");11 }1213 /**

14 Constructor #2 Accepts an Int15 */16

17 public SuperClass2( int arg )18 19 {20 System.out.println ("The following argument was passed to the superclass " +

21 "constructor: " + arg);22 }23 }

Page 16: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-9 (SubClass2.java)

1 public class SubClass2 extends SuperClass22 {3 /**

4 Constructor5 */6

7 public SubClass2()8 {

9 super(10); // What if not included?

10 System.out.println("This is the " +11 "subclass constructor.");12 }13 }

Page 17: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-10 (ConstructorDemo2.java)1 /**

2 This program demonstrates how a superclass

3 constructor is called with the “super” key word.4 */5

6 public class ConstructorDemo27 {

8 public static void main(String[] args)

9 {

10 SubClass2 obj = new SubClass2();11 }12 }

Program OutputProgram Output

The following argument was passed to the superclass constructor: 10

This is the subclass constructor.

Page 18: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-11 (Cube.java)1 /**

2 This class holds data about a cube.3 */4

5 public class Cube extends Rectangle6 {

7 private double height; // The cube's height89 /**

10 The constructor sets the cube's length,11 width, and height.12 @param len The cube's length.13 @param w The cube's width.14 @param h The cube's height.15 */16

17 public Cube(double len, double w, double h)

18 {19 // Call the superclass constructor.

20 super(len, w); // What if SUPER was not coded?21 // WHY? 22 // Set the height. What must you know to answer?

(Continued)

Page 19: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23 height = h;24 }2526 /**

27 The getHeight method returns the cube's height.28 @return The value in the height field.29 */30

31 public double getHeight()32 {33 return height;34 }3536 /**

37 The getSurfaceArea method calculates and38 returns the cube's surface area.39 @return The surface area of the cube.40 */41

42 public double getSurfaceArea()43 {

44 return getArea() * 6; // Where is getArea() defined?(Continued)

Page 20: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

45 }4647 /**

48 The getVolume method calculates and49 returns the cube's volume.50 @return The volume of the cube.51 */52

53 public double getVolume()54 {

55 return getArea() * height;56 }57 }

Page 21: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-12 (CubeDemo.java)1 import java.util.Scanner;23 /**

4 This program demonstrates passing arguments to a5 superclass constructor.6 */7

8 public class CubeDemo9 {

10 public static void main(String[] args)

11 {12 double length; // The cube's length13 double width; // The cube's width14 double height; // The cube's height1516 17 Scanner keyboard = new Scanner(System.in);1819

20 System.out.println("Enter the following " +

21 "dimensions of a cube:");22 System.out.print("Length: ");

(Continued)

Page 22: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23 length = keyboard.nextDouble();2425 26 System.out.print("Width: ");

27 width = keyboard.nextDouble();2829 30 System.out.print("Height: ");

31 height = keyboard.nextDouble();32

33 // Create a cube object 34

35 Cube myCube =

36 new Cube(length, width, height); // Calls SubClass Constructor3738 // Display the cube's properties.

39 System.out.println("Here are the cube's " +40 "properties.");41 System.out.println("Length: " +

42 myCube.getLength()); // Inherited43 System.out.println("Width: " +

44 myCube.getWidth()); // Inherited(Continued)

Page 23: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

45 System.out.println("Height: " +

46 myCube.getHeight()); // Local47 System.out.println("Base Area: " +

48 myCube.getArea()); // Inherited49 System.out.println("Surface Area: " +

50 myCube.getSurfaceArea()); // Local51 System.out.println("Volume: " +

52 myCube.getVolume()); // Local53 }54 }Program Output with Example Input Shown in Bold

Enter the following dimensions of a cube:Length: 10 [Enter]Width: 15 [Enter]Height: 12 [Enter]Here are the cube's properties.Length: 10.0Width: 15.0Height: 12.0

Base Area: 150.0Surface Area: 900.0Volume: 1800.0

Page 24: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-13 (CurvedActivity.java)1 /**

2 This class computes a curved grade. It extends3 the GradedActivity class.4 */5

6 public class CurvedActivity extends GradedActivity7 {8 double rawScore; // Unadjusted score9 double percentage; // Curve percentage1011 /**

12 The constructor sets the curve percentage.13 @param percent The curve percentage.14 */15

16 public CurvedActivity(double percent) // First Calls? - Why?17 { // Does it pass any arguments? 18 percentage = percent;

19 rawScore = 0.0;20 }2122 /**

(Continued)

Page 25: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23 The setScore method overrides the superclass24 setScore method. This version accepts the25 unadjusted score as an argument. That score is26 multiplied by the curve percentage and the27 result is sent as an argument to the superclass's28 setScore method.29 @param s The unadjusted score.30 */31

32 public void setScore(double s)

33 {

34 rawScore = s;

35 super.setScore(rawScore * percentage);36 }3738 /**

39 The getRawScore method returns the raw score.40 @return The value in the rawScore field.41 */42

43 public double getRawScore()44 {

(Continued)

Page 26: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

45 return rawScore;46 }4748 /**

49 The getPercentage method returns the curve50 percentage.51 @return The value in the percentage field.52 */53

54 public double getPercentage()55 {

56 return percentage;57 }58 }

Page 27: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-14 (CurvedActivityDemo.java)1 import java.util.Scanner;23 /**

4 This program demonstrates the CurvedActivity class,

5 which inherits from the GradedActivity class.6 */7

8 public class CurvedActivityDemo9 {

10 public static void main(String[] args)

11 {

12 double score; // Raw score

13 double curvePercent; // Curve percentage1415 16 Scanner keyboard = new Scanner(System.in);1718

19 System.out.print("Enter the student's " +

20 "raw numeric score: ");

21 score = keyboard.nextDouble();

22(Continued)

Page 28: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23

24 System.out.print("Enter the curve percentage: ");

25 curvePercent = keyboard.nextDouble();

2627

28 CurvedActivity curvedExam = new CurvedActivity(curvePercent); // Called?3031

32 curvedExam.setScore(score); // Called which method? Why?3334 // Display the raw score.

35 System.out.println("The raw score is " + curvedExam.getRawScore() +

37 " points.");3839 // Display the curved score.

40 System.out.println("The curved score is " + curvedExam.getScore()); // Inherited.4243 // Display the exam grade.

44 System.out.println("The exam grade is " + curvedExam.getGrade()); // Inherited.

4546 }47 } // end class

Page 29: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Program Output with Example Input Shown in Bold

Enter the student's raw numeric score: 87 [Enter]

Enter the curve percentage: 1.06 [Enter]

The raw score is 87.0 points.The curved score is 92.22The exam grade is A

Page 30: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-15 (SuperClass3.java)

1 public class SuperClass32 {3 /**

4 This method displays an int.5 @param arg An int.6 */7

8 public void showValue( int arg ) // Overridden in subclass

9 { // Can this be called through a subclass

10 // Object? 10 System.out.println("SUPERCLASS: " +

11 "The int argument was " + arg);12 }1314 /**

15 This method displays a String. Is showValue “overloaded in this class?16 @param arg A String.17 */18

19 public void showValue( String arg ) 20 {

21 System.out.println("SUPERCLASS: " +

22 "The String argument was " + arg);

23 }24 }

Page 31: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-16 (SubClass3.java)

1 public class SubClass3 extends SuperClass32 {3 /**

4 This method overrides one of the5 superclass methods.6 @param arg An int.7 */8

9 public void showValue( int arg ) // <-This May be called thru?10 { // <-add super.showvalue(arg);11 // AND What is impact?11 System.out.println("SUBCLASS: " +12 "The int argument was " + arg);13 }1415 /**

16 This method overloads the superclass17 methods.18 @param arg A double.19 */20

21 public void showValue( double arg ) // May be called thru?22 {

(Continued)

Page 32: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23 System.out.println("SUBCLASS: " +

24 "The double argument was " + arg);

25 }26 }

Page 33: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-17 (ShowValueDemo.java)1 /**

2 This program demonstrates the methods in the3 SuperClass3 and SubClass3 classes.4 */5

6 public class ShowValueDemo7 {

8 public static void main(String[] args)

9 {10

11 SubClass3 myObject = new SubClass3();12

13 myObject.showValue( 10 ); // Pass an int. ALL 3 ARE CALLS

14 myObject.showValue( 1.2 ); // Pass a double. THRU A SUBCLASS

15 myObject.showValue( "Hello“ ); // Pass a String. OBJECT.16 }17 }Program Output

SUBCLASS: The int argument was 10 // How would you callSUBCLASS: The double argument was 1.2 // Superclass method

SUPERCLASS: The String argument was Hello // showvalue(int arg) ? See pg. 648(earlier slide)

Page 34: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-18 (GradedActivity2.java)1 /**2 A class that holds a grade for a graded activity.3 */4

5 public class GradedActivity26 {

7 protected double score; // Numeric score

89 /**10 The setScore method sets the score field.11 @param s The value to store in score.12 */13

14 public void setScore(double s)15 {

16 score = s;

17 }1819 /**

20 The getScore method returns the score.21 @return The value stored in the score field.22 */

(Continued)

Page 35: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23

24 public double getScore()25 {

26 return score;

27 }2829 /**30 The getGrade method returns a letter grade31 determined from the score field.32 @return The letter grade.33 */34

35 public char getGrade()36 {

37 char letterGrade;3839 if (score >= 90)40 letterGrade = 'A';41 else if (score >= 80)42 letterGrade = 'B';43 else if (score >= 70)44 letterGrade = 'C';

(Continued)

Page 36: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

45 else if (score >= 60)46 letterGrade = 'D';47 else48 letterGrade = 'F';49

50 return letterGrade;51 }52 }

Page 37: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-19 (FinalExam2.java)1 /**2 This class determines the grade for a final exam.3 The numeric score is rounded up to the next whole4 number if its fractional part is .5 or greater.5 */6

7 public class FinalExam2 extends GradedActivity28 {9 private int numQuestions; // Number of questions10 private double pointsEach; // Points for each question11 private int numMissed; // Number of questions missed1213 /**14 The constructor sets the number of questions on the15 exam and the number of questions missed.16 @param questions The number of questions.17 @param missed The number of questions missed.18 */19 // Constructor Code19 //----------------------------------------------------------------------------------------------------

-20 public FinalExam2( int questions, int missed )21 {22 double numericScore; // To hold a numeric score

(Continued)

Page 38: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23

24 // Set the numQuestions and numMissed fields.

25 numQuestions = questions;26 numMissed = missed;27

28 // Calculate the points for each question and29 // the numeric score for this exam.

30 pointsEach = 100.0 / questions;

31 numericScore = 100.0 - (missed * pointsEach);32

33 // Call the inherited setScore method to34 // set the numeric score.

35 setScore( numericScore ); // Inherited?36

37 // Adjust the score.

38 adjustScore(); // Where is method defined?39

} //---------------------------------------------------------------------------------------------------

4041 /**

42 The getPointsEach method returns the number of43 points each question is worth.44 @return The value in the pointsEach field.

(Continued)

Page 39: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

45 */46

47 public double getPointsEach()48 {

49 return pointsEach;50 }5152 /**53 The getNumMissed method returns the number of54 questions missed.55 @return The value in the numMissed field.56 */57

58 public int getNumMissed()59 {

60 return numMissed;61 }6263 /**64 The adjustScore method adjusts a numeric score.65 If score is within 0.5 points of the next whole66 number, it rounds the score up.

(Continued)

Page 40: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

67 */68

69 private void adjustScore() // Called from constructor

70 { // Why is “score” directly available to this 71 double fraction; // method?72

73 // Get the fractional part of the score.

74 fraction = score - (int) score;75

76 // If the fractional part is .5 or greater,77 // round the score up to the next whole number.

78 if (fraction >= 0.5)

79 score = score + (1.0 - fraction);

80 }

81 } // end class

Page 41: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-20 (ProtectedDemo.java)1 import javax.swing.JOptionPane;23 /**

4 This program demonstrates the FinalExam2 class,5 which extends the GradedActivity2 class.6 */7

8 public class ProtectedDemo9 {

10 public static void main(String[] args)

11 {

12 String input; // To hold input

13 int questions; // Number of questions

14 Int missed; // Number of questions missed1516

17 input = JOptionPane.showInputDialog("How many " +

18 "questions are on the final exam?");

19 questions = Integer.parseInt(input);

2021

22 input = JOptionPane.showInputDialog("How many " +

(Continued)

Page 42: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23 "questions did the student miss?");

24 missed = Integer.parseInt(input);

25

26 // Create a FinalExam object.

27 FinalExam2 exam = new FinalExam2( questions, missed );28

29 // Display the test results.

30 JOptionPane.showMessageDialog(null,

31 "Each question counts " + exam.getPointsEach() +32 " points.\nThe exam score is " +

33 exam.getScore() + "\nThe exam grade is " +

34 exam.getGrade());3536 System.exit(0);37 }38 }

Page 43: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-21 (PassFailActivity.java)1 /**2 This class holds a numeric score and determines3 whether the score is passing or failing.4 */5

6 public class PassFailActivity extends GradedActivity7 {

8 private double minPassingScore; // Minimum passing score910 /**

11 The constructor sets the minimum passing score.12 @param mps The minimum passing score.13 */14

15 public PassFailActivity( double mps )

16 {

17 minPassingScore = mps;18 }1920 /**21 The getGrade method returns a letter grade22 determined from the score field. This

(Continued)

Page 44: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23 method overrides the superclass method.24 @return The letter grade.25 */26

27 public char getGrade() // OVERRIDES supercalss method28 {29 char letterGrade;3031 if (super.getScore() >= minPassingScore)

32 letterGrade = 'P';33 else

34 letterGrade = 'F';35

36 return letterGrade;37 }38 }

Page 45: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-22 (PassFailExam.java)1 /**2 This class determines a passing or failing grade for3 an exam.4 */5

6 public class PassFailExam extends PassFailActivity7 {

8 private int numQuestions; // Number of questions

9 private double pointsEach; // Points for each question

10 private int numMissed; // Number of questions missed1112 /**

13 The constructor sets the number of questions, the14 number of questions missed, and the minimum passing15 score.16 @param questions The number of questions.17 @param missed The number of questions missed.18 @param minPassing The minimum passing score.19 */20

21 public PassFailExam( int questions, int missed,22 double minPassing )

(Continued)

Page 46: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23 {24

25 super( minPassing ); // Does what? Required?2627 /28 double numericScore;2930 // Set the numQuestions and numMissed fields.

31 numQuestions = questions;32 numMissed = missed;3334 // Calculate the points for each question and35 // the numeric score for this exam.

36 pointsEach = 100.0 / questions;37 numericScore = 100.0 - (missed * pointsEach);38

39 // Call the superclass's setScore method to40 // set the numeric score.

41 setScore( numericScore );42 }4344 /**

(Continued)

Page 47: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

45 The getPointsEach method returns the number of46 points each question is worth.47 @return The value in the pointsEach field.48 */49

50 public double getPointsEach()51 {52 return pointsEach;53 }5455 /**56 The getNumMissed method returns the number of57 questions missed.58 @return The value in the numMissed field.59 */60

61 public int getNumMissed()62 {63 return numMissed;64 }65 }

Page 48: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-23 (PassFailExamDemo.java)1 import java.util.Scanner;23 /**

4 This program demonstrates the PassFailExam class.5 */6

7 public class PassFailExamDemo8 {

9 public static void main(String[] args)

10 {

11 int questions; // Number of questions

12 int missed; // Number of questions missed

13 double minPassing // Minimum passing score1415 // Create a Scanner object for keyboard input.16 Scanner keyboard = new Scanner(System.in);1718 // Get the number of questions on the exam.

19 System.out.print("How many questions are " +

20 "on the exam? ");

21 questions = keyboard.nextInt();

22(Continued)

Page 49: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

24 System.out.print("How many questions did " +

25 "the student miss? ");

26 missed = keyboard.nextInt();

2728

29 System.out.print("What is the minimum " +

30 "passing score? ");

31 minPassing = keyboard.nextDouble();

32

33 // Create a PassFailExam object.

34 PassFailExam exam = new PassFailExam( questions, missed, minPassing );

3637 38 System.out.println("Each question counts " +

39 exam.getPointsEach() + " points.");

4041 42 System.out.println("The exam score is " +

43 exam.getScore());44

(Continued)

Page 50: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

45 46 System.out.println("The exam grade is " +

47 exam.getGrade());48 }49 }Program Output with Example Input Shown in Bold

How many questions are on the exam? 100 [Enter]

How many questions did the student miss? 25 [Enter]

What is the minimum passing score? 60 [Enter]

Each question counts 1.0 points.The exam score is 75.0The exam grade is P

Page 51: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-24 (ObjectMethods.java)1 /**2 This program demonstrates the toString and equals3 methods that are inherited from the Object class.4 */5

6 public class ObjectMethods7 {

8 public static void main(String[] args)

9 {10

11 PassFailExam exam1 =

12 new PassFailExam(0, 0, 0);

13 PassFailExam exam2 =14 new PassFailExam(0, 0, 0);1516

18 System.out.println( exam1 );

19 System.out.println( exam2 );2021

22 if (exam1.equals( exam2 )) // TESTS What?(Continued)

Page 52: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23 System.out.println("They are the same.");24 else25 System.out.println("They are not the same.");26 }27 }

Program Output

PassFailExam@16f0472PassFailExam@18d107fThey are not the same.

Page 53: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-25 (Polymorphic.java)1 /**

2 This program demonstrates polymorphic behavior.

3 */4

5 public class Polymorphic6 {

7 public static void main(String[] args)

8 {9

10 GradedActivity[] tests = new GradedActivity[3];1112

14 tests[0] = new GradedActivity();

15 tests[0].setScore(95);1617

20 tests[1] = new PassFailExam(20, 5, 60); // Why no method call to21 // initialize “score”?22 // The third test is the final exam. There were

Page 54: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

23

24 tests[2] = new FinalExam(50, 7);25

26 // Display the grades.

27 for (int i = 0; i < tests.length; i++)28 {29 System.out.println("Test " + (i + 1) + ": " +

30 "score " + tests[i].getScore() +

31 ", grade " + tests[i].getGrade());32 }33 }34 }Program Output

Test 1: score 95.0, grade A

Test 2: score 75.0, grade P // Why “p” grade?Test 3: score 86.0, grade B

Page 55: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-26 (Student.java)1 /**2 The Student class is an abstract class that holds3 general data about a student. Classes representing4 specific types of students should inherit from5 this class.6 */78 public abstract class Student9 {10 private String name; // Student name11 private String idNumber; // Student ID12 private int yearAdmitted; // Year admitted1314 /**15 The constructor sets the student's name,16 ID number, and year admitted.17 @param n The student's name.18 @param id The student's ID number.19 @param year The year the student was admitted.20 */2122 public Student(String n, String id, int year)

(Continued)

Page 56: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-26 (Student.java)23 {24 name = n;25 idNumber = id;26 yearAdmitted = year;27 }2829 /**30 The toString method returns a String containing31 the student's data.32 @return A reference to a String.33 */3435 public String toString()36 {37 String str;3839 str = "Name: " + name40 + "\nID Number: " + idNumber41 + "\nYear Admitted: " + yearAdmitted;42 return str;43 }44

(Continued)

Page 57: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-26 (Student.java)45 /**46 The getRemainingHours method is abstract.47 It must be overridden in a subclass.48 @return The hours remaining for the student.49 */5051 public abstract int getRemainingHours();52 }

Page 58: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-27 (CompSciStudent.java)1 /**2 This class holds data for a computer science student.3 */45 public class CompSciStudent extends Student6 {7 // Required hours8 private final int MATH_HOURS = 20; // Math hours9 private final int CS_HOURS = 40; // Comp sci hours10 private final int GEN_ED_HOURS = 60; // Gen ed hours1112 // Hours taken13 private int mathHours; // Math hours taken14 private int csHours; // Comp sci hours taken15 private int genEdHours; // General ed hours taken1617 /**18 The constructor sets the student's name,19 ID number, and the year admitted.20 @param n The student's name.21 @param id The student's ID number.22 @param year The year the student was admitted.

(Continued)

Page 59: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-27 (CompSciStudent.java)23 */2425 public CompSciStudent(String n, String id, int year)26 {27 super(n, id, year);2829 }3031 /**32 The setMathHours method sets the number of33 math hours taken.34 @param math The math hours taken.35 */3637 public void setMathHours(int math)38 {39 mathHours = math;40 }4142 /**43 The setCsHours method sets the number of44 computer science hours taken.

(Continued)

Page 60: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-27 (CompSciStudent.java)45 @param cs The computer science hours taken.46 */4748 public void setCsHours(int cs)49 {50 csHours = cs;51 }5253 /**54 The setGenEdHours method sets the number of55 general ed hours taken.56 @param genEd The general ed hours taken.57 */5859 public void setGenEdHours(int genEd)60 {61 genEdHours = genEd;62 }6364 /**65 The getRemainingHours method returns the66 number of hours remaining to be taken.

(Continued)

Page 61: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-27 (CompSciStudent.java)67 @return The hours remaining for the student.68 */6970 public int getRemainingHours()71 {72 int reqHours, // Total required hours73 remainingHours; // Remaining hours7475 // Calculate the required hours.76 reqHours = MATH_HOURS + CS_HOURS + GEN_ED_HOURS;7778 // Calculate the remaining hours.79 remainingHours = reqHours - (mathHours + csHours80 + genEdHours);8182 return remainingHours;83 }8485 /**86 The toString method returns a string containing87 the student's data.88 @return A reference to a String.

(Continued)

Page 62: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-27 (CompSciStudent.java)89 */9091 public String toString()92 {93 String str;9495 str = super.toString() +96 "\nMajor: Computer Science" +97 "\nMath Hours Taken: " + mathHours +98 "\nComputer Science Hours Taken: " + csHours +99 "\nGeneral Ed Hours Taken: " + genEdHours;100101 return str;102 }103 }

Page 63: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-28 (CompSciStudentDemo.java)1 /**2 This program demonstrates the CompSciStudent class.3 */45 public class CompSciStudentDemo6 {7 public static void main(String[] args)8 {9 // Create a CompSciStudent object.10 CompSciStudent csStudent =11 new CompSciStudent("Jennifer Haynes",12 "167W98337", 2004);1314 // Store values for math, CS, and gen ed hours.15 csStudent.setMathHours(12);16 csStudent.setCsHours(20);17 csStudent.setGenEdHours(40);1819 // Display the student's data.20 System.out.println(csStudent);2122 // Display the number of remaining hours.

Page 64: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-28 (CompSciStudentDemo.java)23 System.out.println("Hours remaining: " +24 csStudent.getRemainingHours());25 }26 }Program OutputName: Jennifer HaynesID Number: 167W98337Year Admitted: 2004Major: Computer ScienceMath Hours Taken: 12Computer Science Hours Taken: 20General Ed Hours Taken: 40Hours remaining: 48

Page 65: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-29 (Relatable.java)1 /**2 Relatable interface3 */45 public interface Relatable6 {7 boolean equals(GradedActivity g);8 boolean isGreater(GradedActivity g);9 boolean isLess(GradedActivity g);10 }

Page 66: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-30 (FinalExam3.java)1 /**2 This class determines the grade for a final exam.3 */45 public class FinalExam3 extends GradedActivity6 implements Relatable7 {8 private int numQuestions; // Number of questions9 private double pointsEach; // Points for each question10 private int numMissed; // Questions missed1112 /**13 The constructor sets the number of questions on the14 exam and the number of questions missed.15 @param questions The number of questions.16 @param missed The number of questions missed.17 */1819 public FinalExam3(int questions, int missed)20 {21 double numericScore; // To hold a numeric score22

(Continued)

Page 67: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-30 (FinalExam3.java)23 // Set the numQuestions and numMissed fields.24 numQuestions = questions;25 numMissed = missed;2627 // Calculate the points for each question and28 // the numeric score for this exam.29 pointsEach = 100.0 / questions;30 numericScore = 100.0 - (missed * pointsEach);3132 // Call the inherited setScore method to33 // set the numeric score.34 setScore(numericScore);35 }3637 /**38 The getPointsEach method returns the number of39 points each question is worth.40 @return The value in the pointsEach field.41 */4243 public double getPointsEach()44 {

(Continued)

Page 68: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-30 (FinalExam3.java)45 return pointsEach;46 }4748 /**49 The getNumMissed method returns the number of50 questions missed.51 @return The value in the numMissed field.52 */5354 public int getNumMissed()55 {56 return numMissed;57 }5859 /**60 The equals method compares the calling object61 to the argument object for equality.62 @return true if the calling63 object's score is equal to the argument's64 score.65 */66

(Continued)

Page 69: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-30 (FinalExam3.java)67 public boolean equals(GradedActivity g)68 {69 boolean status;7071 if (this.getScore() == g.getScore())72 status = true;73 else74 status = false;7576 return status;77 }7879 /**80 The isGreater method determines whether the calling81 object is greater than the argument object.82 @return true if the calling object's score is83 greater than the argument object's score.84 */8586 public boolean isGreater(GradedActivity g)87 {88 boolean status;

(Continued)

Page 70: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-30 (FinalExam3.java)8990 if (this.getScore() > g.getScore())91 status = true;92 else93 status = false;9495 return status;96 }9798 /**99 The isLess method determines whether the calling100 object is less than the argument object.101 @return true if the calling object's score is102 less than the argument object's score.103 */104105 public boolean isLess(GradedActivity g)106 {107 boolean status;108109 if (this.getScore() < g.getScore())110 status = true;

(Continued)

Page 71: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-30 (FinalExam3.java)111 else112 status = false;113114 return status;115 }116 }

Page 72: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-31 (InterfaceDemo.java)1 /**2 This program demonstrates the FinalExam3 class, which3 implements the Relatable interface.4 */56 public class InterfaceDemo7 {8 public static void main(String[] args)9 {10 // Exam #1 had 100 questions and the student11 // missed 20 questions.12 FinalExam3 exam1 = new FinalExam3(100, 20);1314 // Exam #2 had 100 questions and the student15 // missed 30 questions.16 FinalExam3 exam2 = new FinalExam3(100, 30);1718 // Display the exam scores.19 System.out.println("Exam 1: " +20 exam1.getScore());21 System.out.println("Exam 2: " +22 exam2.getScore());

(Continued)

Page 73: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-31 (InterfaceDemo.java)2324 // Compare the exam scores.25 if (exam1.equals(exam2))26 System.out.println("The exam scores " +27 "are equal.");2829 if (exam1.isGreater(exam2))30 System.out.println("The Exam 1 score " +31 "is the highest.");3233 if (exam1.isLess(exam2))34 System.out.println("The Exam 1 score " +35 "is the lowest.");36 }37 }Program OutputExam 1: 80.0Exam 2: 70.0The Exam 1 score is the highest.

Page 74: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-32 (RetailItem.java)1 /**2 RetailItem interface3 */45 public interface RetailItem6 {7 public double getRetailPrice();8 }

Page 75: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-33 (CompactDisc.java)1 /**2 Compact Disc class3 */45 public class CompactDisc implements RetailItem6 {7 private String title; // The CD's title8 private String artist; // The CD's artist9 private double retailPrice; // The CD's retail price1011 /**12 Constructor13 @param cdTitle The CD title.14 @param cdArtist The name of the artist.15 @param cdPrice The CD's price.16 */1718 public CompactDisc(String cdTitle, String cdArtist,19 double cdPrice)20 {21 title = cdTitle;22 artist = cdArtist;

(Continued)

Page 76: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-33 (CompactDisc.java)23 retailPrice = cdPrice;24 }2526 /**27 getTitle method28 @return The CD's title.29 */3031 public String getTitle()32 {33 return title;34 }3536 /**37 getArtist method38 @return The name of the artist.39 */4041 public String getArtist()42 {43 return artist;44 }

(Continued)

Page 77: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-33 (CompactDisc.java)4546 /**47 getRetailPrice method (Required by the RetailItem48 interface)49 @return The retail price of the CD.50 */5152 public double getRetailPrice()53 {54 return retailPrice;55 }56 }

Page 78: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-34 (DvdMovie.java)1 /**2 DvdMovie class3 */45 public class DvdMovie implements RetailItem6 {7 private String title; // The DVD's title8 private int runningTime; // Running time in minutes9 private double retailPrice; // The DVD's retail price1011 /**12 Constructor13 @param dvdTitle The DVD title.14 @param runTime The running time in minutes.15 @param dvdPrice The DVD's price.16 */1718 public DvdMovie(String dvdTitle, int runTime,19 double dvdPrice)20 {21 title = dvdTitle;22 runningTime = runTime;

(Continued)

Page 79: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-34 (DvdMovie.java)23 retailPrice = dvdPrice;24 }2526 /**27 getTitle method28 @return The DVD's title.29 */3031 public String getTitle()32 {33 return title;34 }3536 /**37 getRunningTime method38 @return The running time in minutes.39 */4041 public int getRunningTime()42 {43 return runningTime;44 }

(Continued)

Page 80: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-34 (DvdMovie.java)4546 /**47 getRetailPrice method (Required by the RetailItem48 interface)49 @return The retail price of the DVD.50 */5152 public double getRetailPrice()53 {54 return retailPrice;55 }56 }

Page 81: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Code Listing 10-35 (PolymorphicInterfaceDemo.java)1 /**2 This program demonstrates that an interface type may3 be used to create a polymorphic reference.4 */56 public class PolymorphicInterfaceDemo7 {8 public static void main(String[] args)9 {10 // Create a CompactDisc object.11 CompactDisc cd =12 new CompactDisc("Greatest Hits",13 "Joe Looney Band",14 18.95);15 // Create a DvdMovie object.16 DvdMovie movie =17 new DvdMovie("Wheels of Fury",18 137, 12.95);1920 // Display the CD's title.21 System.out.println("Item #1: " +22 cd.getTitle());

(Continued)

Page 82: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-35 (PolymorphicInterfaceDemo.java)2324 // Display the CD's price.25 showPrice(cd);2627 // Display the DVD's title.28 System.out.println("Item #2: " +29 movie.getTitle());3031 // Display the DVD's price.32 showPrice(movie);33 }3435 /**36 The showPrice method displays the price37 of a RetailItem object.38 @param item A reference to a RetailItem object.39 */4041 private static void showPrice(RetailItem item)42 {43 System.out.printf("Price: $%,.2f\n", item.getRetailPrice());44 }

(Continued)

Page 83: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

(Continued) Code Listing 10-35 (PolymorphicInterfaceDemo.java)45 }Program OutputItem #1: Greatest HitsPrice: $18.95Item #2: Wheels of FuryPrice: $12.95