Presentation is loading. Please wait.

Presentation is loading. Please wait.

Starting Out with Java: From Control Structures through Objects

Similar presentations


Presentation on theme: "Starting Out with Java: From Control Structures through Objects"— Presentation transcript:

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

2 Code Listing 10-1 (GradedActivity.java)
1 /** A class that holds a grade for a graded activity. General class that will be “extended” later. 3 */ 4 5 public class GradedActivity 6 { 7 private double score; // Numeric score- Data Field 8 9 /** 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 } 18 19 /** 20 The getScore method returns the score. 21 @return The value stored in the score field. 22 */ (Continued)

3 23 24 public double getScore() 25 { 26 return score; 27 } 28 29 /** 30 The getGrade method returns a letter grade 31 determined from the score field. 32 @return The letter grade. 33 */ 34 35 public char getGrade() 36 { 37 char letterGrade; 38 39 if (score >= 90) letterGrade = 'A'; 41 else if (score >= 80) letterGrade = 'B'; 43 else if (score >= 70) letterGrade = 'C'; (Continued)

4 45 else if (score >= 60) letterGrade = 'D'; 47 else letterGrade = 'F'; 49 50 return letterGrade; 51 } 52 }

5 Code Listing 10-2 (GradeDemo.java)
1 import javax.swing.JOptionPane; 2 3 /** 4 This program demonstrates the GradedActivity 5 class. Not a sub class. 6 */ 7 8 public class GradeDemo 9 { 10 public static void main(String[] args) 11 { 12 String input; // To hold input 13 double testScore; // A test score 14 16 GradedActivity grade = new GradedActivity(); // Invokes What? 17 19 Input = JOptionPane.showInputDialog( "Enter " + "a numeric test score."); 21 testScore = Double.parseDouble(input); 22 (Continued)

6 // Store the score in the grade object.
24 grade.setScore(testScore); // Defined where? 25 27 JOptionPane.showMessageDialog(null,"The grade for that test is " + grade.getGrade()); 30 31 System.exit(0); 32 } 33 }

7 Code Listing 10-3 (FinalExam.java)
1 /** This class determines the grade for a final exam. A sub class-inherits what? Does not inherit? 3 */ 4 5 public class FinalExam extends GradedActivity 6 { 7 private int numQuestions; // Number of questions 8 private double pointsEach; // Points for each question 9 private int numMissed; // Questions missed 10 11 /** 12 The constructor sets the number of questions on the 13 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; 21 22 // Set the numQuestions and numMissed fields. (Continued)

8 23 numQuestions = questions;
24 numMissed = missed; 25 26 27 28 pointsEach = / questions; 29 numericScore = (missed * pointsEach); // 3 IV’s are set. 30 33 setScore( numericScore ); // Invokes what? Defined where? Why? 34 } 35 36 /** 37 The getPointsEach method returns the number of 38 points each question is worth. 39 @return The value in the pointsEach field. 40 */ 41 42 public double getPointsEach() 43 { 44 return pointsEach; (Continued)

9 45 } 46 47 /** 48 The getNumMissed method returns the number of 49 questions missed. 50 @return The value in the numMissed field. 51 */ 52 53 public int getNumMissed() // Accessor 54 { 55 return numMissed; 56 } 57 }

10 Code Listing 10-4 (FinalExamDemo.java)
1 import javax.swing.JOptionPane; 2 3 /** 4 This program demonstrates the FinalExam class, 5 which extends the GradedActivity class. 6 */ 7 8 public class FinalExamDemo 9 { 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 missed 15 16 // Get the number of questions on the exam. 17 input = JOptionPane.showInputDialog("How many " + "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)

11 23 "questions did the student miss?");
24 missed = Integer.parseInt(input); 25 27 FinalExam exam = new FinalExam(questions, missed); 28 // Display the test results. 30 JOptionPane.showMessageDialog(null, "Each question counts " + exam.getPointsEach() // Defined where? " points.\nThe exam score is " + exam.getScore() + "\nThe exam grade is " // Defined where? exam.getGrade()); 35 36 System.exit(0); 37 } 38 }

12 Code Listing 10-5 (SuperClass1.java)
1 public class SuperClass1 2 { 3 /** 4 Constructor 5 */ 6 7 public SuperClass1() 8 { 9 System.out.println("This is the " + "superclass constructor."); 11 } 12 }

13 Code Listing 10-6 (SubClass1.java)
1 public class SubClass1 extends SuperClass1 2 { 3 /** 4 Constructor 5 */ 6 7 public SubClass1() 8 { 9 System.out.println("This is the " + "subclass constructor."); 11 } 12 }

14 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 ConstructorDemo1 7 { 8 public static void main(String[] args) 9 { 10 SubClass1 obj = new SubClass1(); 11 } } Program Output This is the superclass constructor. This is the subclass constructor.

15 Code Listing 10-8 (SuperClass2.java)
1 public class SuperClass2 2 { 3 /** 4 Constructor #1 No-ARG 5 */ 6 7 public SuperClass2() 8 { 9 System.out.println("This is the superclass " + "no-arg constructor."); 11 } 12 13 /** 14 Constructor #2 Accepts an Int 15 */ 16 17 public SuperClass2( int arg ) 18 { System.out.println ("The following argument was passed to the superclass " + "constructor: " + arg); 22 } 23 }

16 super(10); // What if not included?
Code Listing 10-9 (SubClass2.java) 1 public class SubClass2 extends SuperClass2 2 { 3 /** 4 Constructor 5 */ 6 7 public SubClass2() 8 { super(10); // What if not included? 10 System.out.println("This is the " + "subclass constructor."); 12 } 13 }

17 Program Output 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 ConstructorDemo2 7 { 8 public static void main(String[] args) 9 { 10 SubClass2 obj = new SubClass2(); 11 } } Program Output The following argument was passed to the superclass constructor: 10 This is the subclass constructor.

18 Code Listing 10-11 (Cube.java)
1 /** 2 This class holds data about a cube. 3 */ 4 5 public class Cube extends Rectangle 6 { 7 private double height; // The cube's height 8 9 /** 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? // WHY? 22 // Set the height What must you know to answer? (Continued)

19 23 height = h; 24 } 25 26 /** 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 } 35 36 /** 37 The getSurfaceArea method calculates and 38 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)

20 45 } 46 47 /** 48 The getVolume method calculates and 49 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 }

21 Code Listing 10-12 (CubeDemo.java)
1 import java.util.Scanner; 2 3 /** 4 This program demonstrates passing arguments to a 5 superclass constructor. 6 */ 7 8 public class CubeDemo 9 { 10 public static void main(String[] args) 11 { 12 double length; // The cube's length 13 double width; // The cube's width 14 double height; // The cube's height 15 16 17 Scanner keyboard = new Scanner(System.in); 18 19 20 System.out.println("Enter the following " + "dimensions of a cube:"); 22 System.out.print("Length: "); (Continued)

22 37 23 length = keyboard.nextDouble(); 24 25
26 System.out.print("Width: "); 27 width = keyboard.nextDouble(); 28 29 30 System.out.print("Height: "); 31 height = keyboard.nextDouble(); 32 33 // Create a cube object 34 35 Cube myCube = new Cube(length, width, height); // Calls SubClass Constructor 37 // Display the cube's properties. 39 System.out.println("Here are the cube's " + "properties."); 41 System.out.println("Length: " + myCube.getLength()); // Inherited 43 System.out.println("Width: " + myCube.getWidth()); // Inherited (Continued)

23 Enter the following dimensions of a cube:
45 System.out.println("Height: " + myCube.getHeight()); // Local 47 System.out.println("Base Area: " + myCube.getArea()); // Inherited 49 System.out.println("Surface Area: " + myCube.getSurfaceArea()); // Local 51 System.out.println("Volume: " + myCube.getVolume()); // Local 53 } 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.0 Width: 15.0 Height: 12.0 Base Area: 150.0 Surface Area: 900.0 Volume:

24 Code Listing 10-13 (CurvedActivity.java)
1 /** 2 This class computes a curved grade. It extends 3 the GradedActivity class. 4 */ 5 6 public class CurvedActivity extends GradedActivity 7 { 8 double rawScore; // Unadjusted score 9 double percentage; // Curve percentage 10 11 /** 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 } 21 22 /** (Continued)

25 23 The setScore method overrides the superclass
24 setScore method. This version accepts the 25 unadjusted score as an argument. That score is 26 multiplied by the curve percentage and the 27 result is sent as an argument to the superclass's 28 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 } 37 38 /** 39 The getRawScore method returns the raw score. 40 @return The value in the rawScore field. 41 */ 42 43 public double getRawScore() 44 { (Continued)

26 45 return rawScore; 46 } 47 48 /** 49 The getPercentage method returns the curve 50 percentage. 51 @return The value in the percentage field. 52 */ 53 54 public double getPercentage() 55 { 56 return percentage; 57 } 58 }

27 Code Listing 10-14 (CurvedActivityDemo.java)
1 import java.util.Scanner; 2 3 /** 4 This program demonstrates the CurvedActivity class, 5 which inherits from the GradedActivity class. 6 */ 7 8 public class CurvedActivityDemo 9 { 10 public static void main(String[] args) 11 { 12 double score; // Raw score 13 double curvePercent; // Curve percentage 14 15 16 Scanner keyboard = new Scanner(System.in); 17 18 19 System.out.print("Enter the student's " + "raw numeric score: "); 21 score = keyboard.nextDouble(); 22 (Continued)

28 42 23 24 System.out.print("Enter the curve percentage: ");
25 curvePercent = keyboard.nextDouble(); 26 27 28 CurvedActivity curvedExam = new CurvedActivity(curvePercent); // Called? 30 31 32 curvedExam.setScore(score); // Called which method? Why? 33 34 // Display the raw score. 35 System.out.println("The raw score is " + curvedExam.getRawScore() + " points."); 38 39 // Display the curved score. 40 System.out.println("The curved score is " + curvedExam.getScore()); // Inherited. 42 43 // Display the exam grade. System.out.println("The exam grade is " + curvedExam.getGrade()); // Inherited. 45 } 47 } // end class

29 The raw score is 87.0 points. The curved score is 92.22
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.22 The exam grade is A

30 Code Listing 10-15 (SuperClass3.java)
1 public class SuperClass3 2 { /** 4 This method displays an int. 5 @param arg An int. 6 */ 7 8 public void showValue( int arg ) // Overridden in subclass { // Can this be called through a subclass // Object? 10 System.out.println("SUPERCLASS: " + "The int argument was " + arg); 12 } 13 14 /** 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 ) { 21 System.out.println("SUPERCLASS: " + "The String argument was " + arg); 23 } 24 }

31 Code Listing 10-16 (SubClass3.java)
1 public class SubClass3 extends SuperClass3 2 { 3 /** 4 This method overrides one of the 5 superclass methods. 6 @param arg An int. 7 */ 8 9 public void showValue( int arg ) // <-This May be called thru? { // <-add super.showvalue(arg); // AND What is impact? 11 System.out.println("SUBCLASS: " + "The int argument was " + arg); 13 } 14 15 /** 16 This method overloads the superclass 17 methods. 18 @param arg A double. 19 */ 20 21 public void showValue( double arg ) // May be called thru? 22 { (Continued)

32 23 System.out.println("SUBCLASS: " +
"The double argument was " + arg); 25 } 26 }

33 Code Listing 10-17 (ShowValueDemo.java)
1 /** 2 This program demonstrates the methods in the 3 SuperClass3 and SubClass3 classes. 4 */ 5 6 public class ShowValueDemo 7 { 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 // How would you call SUBCLASS: The double argument was // Superclass method SUPERCLASS: The String argument was Hello // showvalue(int arg) ? See pg. 648(earlier slide)

34 Code Listing 10-18 (GradedActivity2.java)
1 /** 2 A class that holds a grade for a graded activity. 3 */ 4 5 public class GradedActivity2 6 { 7 protected double score; // Numeric score 8 9 /** 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 } 18 19 /** 20 The getScore method returns the score. 21 @return The value stored in the score field. 22 */ (Continued)

35 23 24 public double getScore() 25 { 26 return score; 27 } 28 29 /** 30 The getGrade method returns a letter grade 31 determined from the score field. 32 @return The letter grade. 33 */ 34 35 public char getGrade() 36 { 37 char letterGrade; 38 39 if (score >= 90) letterGrade = 'A'; 41 else if (score >= 80) letterGrade = 'B'; 43 else if (score >= 70) letterGrade = 'C'; (Continued)

36 45 else if (score >= 60) letterGrade = 'D'; 47 else letterGrade = 'F'; 49 50 return letterGrade; 51 } 52 }

37 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 whole 4 number if its fractional part is .5 or greater. 5 */ 6 7 public class FinalExam2 extends GradedActivity2 8 { 9 private int numQuestions; // Number of questions 10 private double pointsEach; // Points for each question 11 private int numMissed; // Number of questions missed 12 13 /** 14 The constructor sets the number of questions on the 15 exam and the number of questions missed. 16 @param questions The number of questions. 17 @param missed The number of questions missed. */ // Constructor Code 19 // 20 public FinalExam2( int questions, int missed ) 21 { 22 double numericScore; // To hold a numeric score (Continued)

38 // Set the numQuestions and numMissed fields.
23 // Set the numQuestions and numMissed fields. 25 numQuestions = questions; 26 numMissed = missed; 27 28 // Calculate the points for each question and // the numeric score for this exam. 30 pointsEach = / questions; 31 numericScore = (missed * pointsEach); 32 33 // Call the inherited setScore method to // set the numeric score. 35 setScore( numericScore ); // Inherited? 36 // Adjust the score. 38 adjustScore(); // Where is method defined? 39 } // 40 41 /** 42 The getPointsEach method returns the number of 43 points each question is worth. 44 @return The value in the pointsEach field. (Continued)

39 45 */ 46 47 public double getPointsEach() 48 { 49 return pointsEach; 50 } 51 52 /** 53 The getNumMissed method returns the number of 54 questions missed. 55 @return The value in the numMissed field. 56 */ 57 58 public int getNumMissed() 59 { 60 return numMissed; 61 } 62 63 /** 64 The adjustScore method adjusts a numeric score. 65 If score is within 0.5 points of the next whole 66 number, it rounds the score up. (Continued)

40 // Get the fractional part of the score.
67 */ 68 69 private void adjustScore() // Called from constructor 70 { // Why is “score” directly available to this 71 double fraction; // method? 72 // Get the fractional part of the score. 74 fraction = score - (int) score; 75 76 // If the fractional part is .5 or greater, // round the score up to the next whole number. 78 if (fraction >= 0.5) score = score + (1.0 - fraction); 80 } 81 } // end class

41 Code Listing 10-20 (ProtectedDemo.java)
1 import javax.swing.JOptionPane; 2 3 /** 4 This program demonstrates the FinalExam2 class, 5 which extends the GradedActivity2 class. 6 */ 7 8 public class ProtectedDemo 9 { 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 missed 15 16 17 input = JOptionPane.showInputDialog("How many " + "questions are on the final exam?"); 19 questions = Integer.parseInt(input); 20 21 22 input = JOptionPane.showInputDialog("How many " + (Continued)

42 23 "questions did the student miss?");
24 missed = Integer.parseInt(input); 25 // Create a FinalExam object. 27 FinalExam2 exam = new FinalExam2( questions, missed ); 28 // Display the test results. 30 JOptionPane.showMessageDialog(null, "Each question counts " + exam.getPointsEach() + " points.\nThe exam score is " + exam.getScore() + "\nThe exam grade is " + exam.getGrade()); 35 36 System.exit(0); 37 } 38 }

43 Code Listing 10-21 (PassFailActivity.java)
1 /** 2 This class holds a numeric score and determines 3 whether the score is passing or failing. 4 */ 5 6 public class PassFailActivity extends GradedActivity 7 { 8 private double minPassingScore; // Minimum passing score 9 10 /** 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 } 19 20 /** 21 The getGrade method returns a letter grade 22 determined from the score field. This (Continued)

44 23 method overrides the superclass method.
24 @return The letter grade. 25 */ 26 27 public char getGrade() // OVERRIDES superclass method 28 { 29 char letterGrade; 30 31 if (super.getScore() >= minPassingScore) letterGrade = 'P'; 33 else letterGrade = 'F'; 35 36 return letterGrade; 37 } 38 }

45 Code Listing 10-22 (PassFailExam.java)
1 /** 2 This class determines a passing or failing grade for 3 an exam. 4 */ 5 6 public class PassFailExam extends PassFailActivity 7 { 8 private int numQuestions; // Number of questions 9 private double pointsEach; // Points for each question 10 private int numMissed; // Number of questions missed 11 12 /** 13 The constructor sets the number of questions, the 14 number of questions missed, and the minimum passing 15 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, double minPassing ) (Continued)

46 // set the numeric score.
23 { 24 25 super( minPassing ); // Does what? Required? 26 27 / 28 double numericScore; 29 // Set the numQuestions and numMissed fields. 31 numQuestions = questions; 32 numMissed = missed; 33 34 // Calculate the points for each question and // the numeric score for this exam. 36 pointsEach = / questions; 37 numericScore = (missed * pointsEach); 38 39 // Call the superclass's setScore method to // set the numeric score. 41 setScore( numericScore ); // Calls what? Why? Back to? 42 } 43 44 /** (Continued)

47 45 The getPointsEach method returns the number of
46 points each question is worth. 47 @return The value in the pointsEach field. 48 */ 49 50 public double getPointsEach() 51 { 52 return pointsEach; 53 } 54 55 /** 56 The getNumMissed method returns the number of 57 questions missed. 58 @return The value in the numMissed field. 59 */ 60 61 public int getNumMissed() 62 { 63 return numMissed; 64 } 65 }

48 Code Listing 10-23 (PassFailExamDemo.java)
1 import java.util.Scanner; 2 3 /** 4 This program demonstrates the PassFailExam class. 5 */ 6 7 public class PassFailExamDemo 8 { 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 score 14 15 // Create a Scanner object for keyboard input. 16 Scanner keyboard = new Scanner(System.in); 17 18 // Get the number of questions on the exam. 19 System.out.print("How many questions are " + "on the exam? "); 21 questions = keyboard.nextInt(); 22 (Continued)

49 24 System.out.print("How many questions did " +
"the student miss? "); 26 missed = keyboard.nextInt(); 27 28 29 System.out.print("What is the minimum " + "passing score? "); 31 minPassing = keyboard.nextDouble(); 32 // Create a PassFailExam object. 34 PassFailExam exam = new PassFailExam( questions, missed, minPassing ); 36 37 38 System.out.println("Each question counts " + exam.getPointsEach() + " points."); 40 41 42 System.out.println("The exam score is " + exam.getScore()); 44 (Continued)

50 Each question counts 1.0 points. The exam score is 75.0
45 46 System.out.println("The exam grade is " + 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.0 The exam grade is P

51 Code Listing 10-24 (ObjectMethods.java)
1 /** 2 This program demonstrates the toString and equals 3 methods that are inherited from the Object class. 4 */ 5 6 public class ObjectMethods 7 { 8 public static void main(String[] args) 9 { 10 11 PassFailExam exam1 = new PassFailExam(0, 0, 0); 13 PassFailExam exam2 = new PassFailExam(0, 0, 0); 15 16 18 System.out.println( exam1 ); 19 System.out.println( exam2 ); 20 21 22 if (exam1.equals( exam2 )) // TESTS What? (Continued)

52 PassFailExam@16f0472 PassFailExam@18d107f They are not the same.
System.out.println("They are the same."); 24 else System.out.println("They are not the same."); 26 } } Program Output They are not the same.

53 Code Listing 10-25 (Polymorphic.java)
1 /** 2 This program demonstrates polymorphic behavior. 3 */ 4 5 public class Polymorphic 6 { 7 public static void main(String[] args) 8 { 9 10 GradedActivity[ ] tests = new GradedActivity[3]; 11 12 14 tests[0] = new GradedActivity(); 15 tests[0].setScore(95); 16 17 20 tests[1] = new PassFailExam(20, 5, 60); // Why no method call to // initialize “score”? 22 // The third test is the final exam. There were

54 Test 2: score 75.0, grade P // Why “p” grade?
23 24 tests[2] = new FinalExam(50, 7); 25 // Display the grades. 27 for (int i = 0; i < tests.length; i++) 28 { System.out.println("Test " + (i + 1) + ": " + "score " + tests[i].getScore() + ", 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

55 Code Listing 10-26 (Student.java)
1 /** 2 The Student class is an abstract class that holds 3 general data about a student. Classes representing 4 specific types of students should inherit from 5 this class. 6 */ 7 8 public abstract class Student 9 { 10 private String name; // Student name 11 private String idNumber; // Student ID 12 private int yearAdmitted; // Year admitted 13 14 /** 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 */ 21 22 public Student(String n, String id, int year) (Continued)

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

57 (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 */ 50 51 public abstract int getRemainingHours(); 52 }

58 Code Listing 10-27 (CompSciStudent.java)
1 /** 2 This class holds data for a computer science student. 3 */ 4 5 public class CompSciStudent extends Student 6 { 7 // Required hours 8 private final int MATH_HOURS = 20; // Math hours 9 private final int CS_HOURS = 40; // Comp sci hours 10 private final int GEN_ED_HOURS = 60; // Gen ed hours 11 12 // Hours taken 13 private int mathHours; // Math hours taken 14 private int csHours; // Comp sci hours taken 15 private int genEdHours; // General ed hours taken 16 17 /** 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)

59 (Continued) Code Listing 10-27 (CompSciStudent.java)
23 */ 24 25 public CompSciStudent(String n, String id, int year) 26 { 27 super(n, id, year); 28 29 } 30 31 /** 32 The setMathHours method sets the number of 33 math hours taken. 34 @param math The math hours taken. 35 */ 36 37 public void setMathHours(int math) 38 { 39 mathHours = math; 40 } 41 42 /** 43 The setCsHours method sets the number of 44 computer science hours taken. (Continued)

60 (Continued) Code Listing 10-27 (CompSciStudent.java)
45 @param cs The computer science hours taken. 46 */ 47 48 public void setCsHours(int cs) 49 { 50 csHours = cs; 51 } 52 53 /** 54 The setGenEdHours method sets the number of 55 general ed hours taken. 56 @param genEd The general ed hours taken. 57 */ 58 59 public void setGenEdHours(int genEd) 60 { 61 genEdHours = genEd; 62 } 63 64 /** 65 The getRemainingHours method returns the 66 number of hours remaining to be taken. (Continued)

61 (Continued) Code Listing 10-27 (CompSciStudent.java)
67 @return The hours remaining for the student. 68 */ 69 70 public int getRemainingHours() 71 { 72 int reqHours, // Total required hours remainingHours; // Remaining hours 74 75 76 reqHours = MATH_HOURS + CS_HOURS + GEN_ED_HOURS; 77 78 / 79 remainingHours = reqHours - (mathHours + csHours genEdHours); 81 82 return remainingHours; 83 } 84 85 /** 86 The toString method returns a string containing 87 the student's data. 88 @return A reference to a String. (Continued)

62 (Continued) Code Listing 10-27 (CompSciStudent.java)
89 */ 90 91 public String toString() 92 { 93 String str; 94 95 str = super.toString() + "\nMajor: Computer Science" + "\nMath Hours Taken: " + mathHours + "\nComputer Science Hours Taken: " + csHours + "\nGeneral Ed Hours Taken: " + genEdHours; 100 101 return str; 102 } 103 }

63 Code Listing 10-28 (CompSciStudentDemo.java)
1 /** 2 This program demonstrates the CompSciStudent class. 3 */ 4 5 public class CompSciStudentDemo 6 { 7 public static void main(String[] args) 8 { 9 10 CompSciStudent csStudent = new CompSciStudent("Jennifer Haynes", "167W98337", 2004); 13 15 csStudent.setMathHours(12); 16 csStudent.setCsHours(20); 17 csStudent.setGenEdHours(40); 18 19 20 System.out.println(csStudent); 21 22 // Display the number of remaining hours.

64 23 System.out.println("Hours remaining: " +
24 csStudent.getRemainingHours()); 25 } } Program Output Name: Jennifer Haynes ID Number: 167W98337 Year Admitted: 2004 Major: Computer Science Math Hours Taken: 12 Computer Science Hours Taken: 20 General Ed Hours Taken: 40 Hours remaining: 48

65 5 public interface Relatable 6 { 7 boolean equals(GradedActivity g);
Code Listing (Relatable.java) 1 /** 2 Relatable interface 3 */ 4 5 public interface Relatable 6 { 7 boolean equals(GradedActivity g); 8 boolean isGreater(GradedActivity g); 9 boolean isLess(GradedActivity g); } Note: No access modifier-all specified in Interface are public.

66 Code Listing 10-30 (FinalExam3.java)
1 /** 2 This class determines the grade for a final exam. 3 */ 4 5 public class FinalExam3 extends GradedActivity implements Relatable 7 { 8 private int numQuestions; // Number of questions 9 private double pointsEach; // Points for each question 10 private int numMissed; // Questions missed 11 12 /** 13 The constructor sets the number of questions on the 14 exam and the number of questions missed. 15 @param questions The number of questions. 16 @param missed The number of questions missed. 17 */ 18 19 public FinalExam3(int questions, int missed) 20 { 21 double numericScore; // To hold a numeric score 22 (Continued)

67 (Continued) Code Listing 10-30 (FinalExam3.java)
23 // Set the numQuestions and numMissed fields. 24 numQuestions = questions; 25 numMissed = missed; 26 27 // Calculate the points for each question and 28 // the numeric score for this exam. 29 pointsEach = / questions; 30 numericScore = (missed * pointsEach); 31 32 // Call the inherited setScore method to 33 // set the numeric score. 34 setScore(numericScore); 35 } 36 37 /** 38 The getPointsEach method returns the number of 39 points each question is worth. 40 @return The value in the pointsEach field. 41 */ 42 43 public double getPointsEach() 44 { (Continued)

68 (Continued) Code Listing 10-30 (FinalExam3.java)
45 return pointsEach; 46 } 47 48 /** 49 The getNumMissed method returns the number of 50 questions missed. 51 @return The value in the numMissed field. 52 */ 53 54 public int getNumMissed() 55 { 56 return numMissed; 57 } 58 59 /** 60 The equals method compares the calling object 61 to the argument object for equality. 62 @return true if the calling 63 object's score is equal to the argument's 64 score. 65 */ 66 (Continued)

69 (Continued) Code Listing 10-30 (FinalExam3.java)
67 public boolean equals(GradedActivity g) 68 { 69 boolean status; 70 71 if (this.getScore() == g.getScore()) status = true; 73 else status = false; 75 76 return status; 77 } 78 79 /** 80 The isGreater method determines whether the calling 81 object is greater than the argument object. 82 @return true if the calling object's score is 83 greater than the argument object's score. 84 */ 85 86 public boolean isGreater(GradedActivity g) 87 { 88 boolean status; (Continued)

70 (Continued) Code Listing 10-30 (FinalExam3.java)
89 90 if (this.getScore() > g.getScore()) status = true; 92 else status = false; 94 95 return status; 96 } 97 98 /** 99 The isLess method determines whether the calling 100 object is less than the argument object. 101 @return true if the calling object's score is 102 less than the argument object's score. 103 */ 104 105 public boolean isLess(GradedActivity g) 106 { 107 boolean status; 108 109 if (this.getScore() < g.getScore()) status = true; (Continued)

71 (Continued) Code Listing 10-30 (FinalExam3.java)
111 else status = false; 113 114 return status; 115 } 116 }

72 Code Listing 10-31 (InterfaceDemo.java)
1 /** 2 This program demonstrates the FinalExam3 class, which 3 implements the Relatable interface. 4 */ 5 6 public class InterfaceDemo 7 { 8 public static void main(String[] args) 9 { 10 // Exam #1 had 100 questions and the student 11 // missed 20 questions. 12 FinalExam3 exam1 = new FinalExam3(100, 20); 13 14 // Exam #2 had 100 questions and the student 15 // missed 30 questions. 16 FinalExam3 exam2 = new FinalExam3(100, 30); 17 18 // Display the exam scores. 19 System.out.println("Exam 1: " + exam1.getScore()); 21 System.out.println("Exam 2: " + exam2.getScore()); (Continued)

73 (Continued) Code Listing 10-31 (InterfaceDemo.java)
23 24 // Compare the exam scores. 25 if (exam1.equals(exam2)) System.out.println("The exam scores " + "are equal."); 28 29 if (exam1.isGreater(exam2)) System.out.println("The Exam 1 score " + "is the highest."); 32 33 if (exam1.isLess(exam2)) System.out.println("The Exam 1 score " + "is the lowest."); 36 } 37 } Program Output Exam 1: 80.0 Exam 2: 70.0 The Exam 1 score is the highest.

74 Code Listing 10-32 (RetailItem.java)
1 /** 2 RetailItem interface 3 */ 4 5 public interface RetailItem 6 { 7 public double getRetailPrice(); 8 }

75 Code Listing 10-33 (CompactDisc.java)
1 /** 2 Compact Disc class 3 */ 4 5 public class CompactDisc implements RetailItem 6 { 7 private String title; // The CD's title 8 private String artist; // The CD's artist 9 private double retailPrice; // The CD's retail price 10 11 /** 12 Constructor 13 @param cdTitle The CD title. 14 @param cdArtist The name of the artist. 15 @param cdPrice The CD's price. 16 */ 17 18 public CompactDisc(String cdTitle, String cdArtist, double cdPrice) 20 { 21 title = cdTitle; 22 artist = cdArtist; (Continued)

76 (Continued) Code Listing 10-33 (CompactDisc.java)
23 retailPrice = cdPrice; 24 } 25 26 /** 27 getTitle method 28 @return The CD's title. 29 */ 30 31 public String getTitle() 32 { 33 return title; 34 } 35 36 /** 37 getArtist method 38 @return The name of the artist. 39 */ 40 41 public String getArtist() 42 { 43 return artist; 44 } (Continued)

77 (Continued) Code Listing 10-33 (CompactDisc.java)
45 46 /** 47 getRetailPrice method (Required by the RetailItem 48 interface) 49 @return The retail price of the CD. 50 */ 51 52 public double getRetailPrice() 53 { 54 return retailPrice; 55 } 56 }

78 Code Listing 10-34 (DvdMovie.java)
1 /** 2 DvdMovie class 3 */ 4 5 public class DvdMovie implements RetailItem 6 { 7 private String title; // The DVD's title 8 private int runningTime; // Running time in minutes 9 private double retailPrice; // The DVD's retail price 10 11 /** 12 Constructor 13 @param dvdTitle The DVD title. 14 @param runTime The running time in minutes. 15 @param dvdPrice The DVD's price. 16 */ 17 18 public DvdMovie(String dvdTitle, int runTime, double dvdPrice) 20 { 21 title = dvdTitle; 22 runningTime = runTime; (Continued)

79 (Continued) Code Listing 10-34 (DvdMovie.java)
23 retailPrice = dvdPrice; 24 } 25 26 /** 27 getTitle method 28 @return The DVD's title. 29 */ 30 31 public String getTitle() 32 { 33 return title; 34 } 35 36 /** 37 getRunningTime method 38 @return The running time in minutes. 39 */ 40 41 public int getRunningTime() 42 { 43 return runningTime; 44 } (Continued)

80 (Continued) Code Listing 10-34 (DvdMovie.java)
45 46 /** 47 getRetailPrice method (Required by the RetailItem 48 interface) 49 @return The retail price of the DVD. 50 */ 51 52 public double getRetailPrice() 53 { 54 return retailPrice; 55 } 56 }

81 Code Listing 10-35 (PolymorphicInterfaceDemo.java)
1 /** 2 This program demonstrates that an interface type may 3 be used to create a polymorphic reference. 4 */ 5 6 public class PolymorphicInterfaceDemo 7 { 8 public static void main(String[] args) 9 { 10 // Create a CompactDisc object. 11 CompactDisc cd = new CompactDisc("Greatest Hits", "Joe Looney Band", ); 15 // Create a DvdMovie object. 16 DvdMovie movie = new DvdMovie("Wheels of Fury", , 12.95); 19 20 // Display the CD's title. 21 System.out.println("Item #1: " + cd.getTitle()); (Continued)

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

83 (Continued) Code Listing 10-35 (PolymorphicInterfaceDemo.java)
45 } Program Output Item #1: Greatest Hits Price: $18.95 Item #2: Wheels of Fury Price: $12.95


Download ppt "Starting Out with Java: From Control Structures through Objects"

Similar presentations


Ads by Google