Code Listing 10-30 (FinalExam3.java)

advertisement
Starting Out with Java:
From Control Structures
through Objects
5th edition
By Tony Gaddis
Source Code: Chapter 10
Code Listing 10-1 (GradedActivity.java)
1
/**
2
3
3
4
5
6
A class that holds a grade for a graded activity. General class that
will be “extended” later.
*/
public class GradedActivity
{
7
8
9
10
11
12
13
private double score;
14
15
public void setScore( double
{
16
17
18
19
20
21
22
// Numeric score- Data Field
/**
The setScore method sets the score field.
@param s The value to store in score.
*/
s)
// Note: NO CONSTRUCTOR Explicit.
score = s;
}
/**
The getScore method returns the score.
@return The value stored in the score field.
*/
(Continued)
23
24
25
public double getScore()
{
26
27
28
29
30
31
32
33
34
return score;
35
36
37
38
39
40
41
42
43
44
}
/**
The getGrade method returns a letter grade
determined from the score field.
@return The letter grade.
*/
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
(Continued)
45
46
47
48
49
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
50
51 }
52 }
return letterGrade;
Code Listing 10-2 (GradeDemo.java)
1
2
3
4
5
6
7
8
9
10
11
12
import javax.swing.JOptionPane;
13
14
double testScore;
15
16
17
18
19
20
21
22
/**
This program demonstrates the GradedActivity
class. Not a sub class.
*/
public class GradeDemo
{
public static void main(String[] args)
{
String input;
// To hold input
// A test score
// Create a GradedActivity object.
GradedActivity grade = new GradedActivity();
//
Invokes What?
// Get a test score.
Input = JOptionPane.showInputDialog("Enter " +
"a numeric test score.");
testScore = Double.parseDouble(input);
(Continued)
23
// Store the score in the grade object.
24
grade setScore(testScore);
.
// Defined where?
25
26
// Display the letter grade for the score.
27
28
JOptionPane.showMessageDialog(null,
"The grade for that test is " +
grade.getGrade());
29
30
31
32 }
33 }
System.exit(0);
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
6
public class FinalExam extends GradedActivity
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
private int
numQuestions;
private double pointsEach;
private int
numMissed;
// Number of questions
// Points for each question
// Questions missed
/**
The constructor sets the number of questions on the
exam and the number of questions missed.
@param questions The number of questions.
@param missed The number of questions missed.
*/
public FinalExam( int questions, int missed )
//
{
double numericScore;
// To hold a numeric score
// Set the
What is executed FIRST?
numQuestions and numMissed fields.
(Continued)
numQuestions = questions;
numMissed = missed;
23
24
25
26
27
28
pointsEach = 100.0 / questions;
numericScore = 100.0 - (missed * pointsEach);
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 3 IV’s are set.
// Call the inherited setScore method to
// set the numeric score.
setScore( numericScore );
//
Invokes what? Defined where? Why?
}
/**
The getPointsEach method returns the number of
points each question is worth.
@return The value in the pointsEach field.
*/
public double getPointsEach()
{
// Accessor
return pointsEach;
(Continued)
45
46
47
48
49
50
51
52
}
53
54
public int getNumMissed()
{
/**
The getNumMissed method returns the number of
questions missed.
@return The value in the numMissed field.
*/
55
56 }
57 }
return numMissed;
// Accessor
Code Listing 10-4 (FinalExamDemo.java)
1
2
3
import javax.swing.JOptionPane;
4
5
6
7
8
9
This program demonstrates the
which extends the GradedActivity class.
*/
10
11
12
13
14
15
/**
FinalExam class,
public class FinalExamDemo
{
public static void main(String[] args)
{
String input;
// To hold input
int questions;
// Number of questions
int missed;
// Number of questions missed
16
// Get the number of questions on the exam.
17
18
19
20
input = JOptionPane.showInputDialog("How many " +
21
// Get the number of questions the student missed.
22
input = JOptionPane.showInputDialog("How many " +
"questions are on the final exam?");
questions = Integer.parseInt(input);
(Continued)
23
24
25
26
"questions did the student miss?");
missed = Integer.parseInt(input);
// Create a FinalExam object.
27
28
FinalExam exam = new FinalExam(questions, missed);
29
// Display the test results.
30
JOptionPane.showMessageDialog(null,
31
32
"Each question counts " + exam.getPointsEach() +
" points.\nThe exam score is " +
// Defined where?
33
exam.getScore() + "\nThe exam grade is " +
exam.getGrade());
// Defined where?
34
35
36
37 }
38 }
System.exit(0);
Code Listing 10-5 (SuperClass1.java)
1 public class SuperClass1
2
3
4
5
6
7
8
{
/**
Constructor
*/
public SuperClass1()
{
9
10
11 }
12 }
System.out.println("This is the " +
"superclass constructor.");
Code Listing 10-6 (SubClass1.java)
1 public class SubClass1 extends SuperClass1
2
3
4
5
6
7
8
{
/**
Constructor
*/
public SubClass1()
{
9
10
11 }
12 }
System.out.println("This is the " +
"subclass constructor.");
Code Listing 10-7 (ConstructorDemo1.java)
1
/**
2
3
4
5
This program demonstrates the order in which
superclass and subclass constructors are called.
*/
6
7
public class ConstructorDemo1
8
9
{
public static void
{
10
11 }
12 }
main(String[] args)
SubClass1 obj = new SubClass1();
Program Output
This is the superclass constructor.
This is the subclass constructor.
Code Listing 10-8 (SuperClass2.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class SuperClass2
{
/**
Constructor #1 No-ARG
*/
public SuperClass2()
{
System.out.println("This is the superclass " +
"no-arg constructor.");
}
/**
Constructor #2 Accepts an Int
*/
17 public SuperClass2( int arg )
18
19 {
20
System.out.println ("The following argument was passed to the superclass " +
21
22 }
23 }
"constructor: " + arg);
Code Listing 10-9 (SubClass2.java)
1
2
3
4
5
6
7
8
public class SubClass2 extends SuperClass2
{
/**
Constructor
*/
public SubClass2()
{
9
super(10);
10
System.out.println("This is the " +
"subclass constructor.");
11
12 }
13 }
// What if not included?
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
7
public class ConstructorDemo2
8
9
public static void main(String[] args)
{
{
10
11 }
12 }
SubClass2 obj = new SubClass2();
Program Output
The following argument was passed to the superclass constructor: 10
This is the subclass constructor.
Code Listing 10-11 (Cube.java)
1
2
3
4
/**
This class holds data about a cube.
*/
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
18
19
20
public Cube(double len, double w, double h)
{
// Call the superclass constructor.
super(len, w);
21
22
// Set the height.
// What if SUPER was not coded?
//
WHY?
What must you know to answer?
(Continued)
23
24
25
26
27
28
29
30
height = h;
}
/**
The getHeight method returns the cube's height.
@return The value in the height field.
*/
31
32
33
34
35
36
37
38
39
40
41
public double getHeight()
{
return height;
}
42
43
public double getSurfaceArea()
{
44
/**
The getSurfaceArea method calculates and
returns the cube's surface area.
@return The surface area of the cube.
*/
return getArea()
* 6;
// Where is getArea() defined?
(Continued)
45
46
47
48
49
50
51
52
}
53
54
public double getVolume()
{
/**
The getVolume method calculates and
returns the cube's volume.
@return The volume of the cube.
*/
55
56 }
57 }
return getArea()
* height;
Code Listing 10-12 (CubeDemo.java)
1
2
3
import java.util.Scanner;
/**
This program demonstrates passing arguments to a
superclass constructor.
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
*/
public class CubeDemo
{
public static void main(String[] args)
{
double length;
// The cube's length
double width;
// The cube's width
double height;
// The cube's height
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the following " +
"dimensions of a cube:");
System.out.print("Length: ");
(Continued)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
length = keyboard.nextDouble();
System.out.print("Width: ");
width = keyboard.nextDouble();
System.out.print("Height: ");
height = keyboard.nextDouble();
// Create
a cube object
Cube myCube =
new Cube(length, width, height); // Calls SubClass Constructor
37
38
// Display
the cube's properties.
39
40
41
42
43
44
System.out.println("Here are the cube's " +
"properties.");
System.out.println("Length: " +
myCube.getLength()); // Inherited
System.out.println("Width: " +
myCube.getWidth());
// Inherited
(Continued)
45
System.out.println("Height: " +
46
myCube.getHeight());
47
System.out.println("Base Area: " +
48
myCube.getArea());
49
System.out.println("Surface Area: " +
50
myCube.getSurfaceArea());
51
System.out.println("Volume: " +
52
myCube.getVolume());
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: 1800.0
// Local
// Inherited
// Local
//
Local
Code Listing 10-13 (CurvedActivity.java)
1
2
3
4
5
/**
This class computes a curved grade. It extends
the GradedActivity class.
*/
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)
17
{
percentage = percent;
rawScore = 0.0;
18
19
20
21
22
// First Calls? - Why?
// Does it pass any arguments?
}
/**
(Continued)
23
The setScore method overrides the superclass
24
25
26
27
28
29
30
31
setScore method. This version accepts the
32
33
unadjusted score as an argument. That score is
multiplied by the curve percentage and the
result is sent as an argument to the superclass's
setScore method.
@param s The unadjusted score.
*/
public void setScore(double s)
{
rawScore = s;
super.setScore(rawScore * percentage);
34
35
36
37
38
39
40
41
42
43
44
}
/**
The getRawScore method returns the raw score.
@return The value in the rawScore field.
*/
public double getRawScore()
{
(Continued)
45
46
47
48
49
50
51
52
53
return rawScore;
}
/**
The getPercentage method returns the curve
percentage.
@return The value in the percentage field.
*/
54 public double getPercentage()
55 {
56
return percentage;
57 }
58 }
Code Listing 10-14 (CurvedActivityDemo.java)
1
2
3
import java.util.Scanner;
/**
This program demonstrates the CurvedActivity
class,
which inherits from the GradedActivity class.
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
*/
public class CurvedActivityDemo
{
public static void main(String[] args)
{
double score;
// Raw score
double curvePercent;
// Curve percentage
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the student's " +
"raw numeric score: ");
score = keyboard.nextDouble();
(Continued)
23
24
System.out.print("Enter the curve percentage: ");
25
26
27
curvePercent = keyboard.nextDouble();
28
30
31
CurvedActivity curvedExam = new CurvedActivity(curvePercent);
32
curvedExam.setScore(score);
33
34
// Display the raw score.
// Called?
// Called which method? Why?
35
37
38
39
System.out.println("The raw score is " + curvedExam.getRawScore() +
" points.");
40
System.out.println("The curved score is " + curvedExam.getScore());
// Display the curved score.
// Inherited.
42
43
// Display the exam grade.
44
System.out.println("The exam grade is " + curvedExam.getGrade());
45
46 }
47 } // end class
// Inherited.
Program Output with Example Input Shown in Bold
Enter the student's raw numeric score:
Enter the curve percentage:
87 [Enter]
1.06 [Enter]
The raw score is 87.0 points.
The curved score is 92.22
The exam grade is A
Code Listing 10-15 (SuperClass3.java)
1
public class SuperClass3
2
3
{
/**
This method displays an int.
@param arg An int.
4
5
6
7
*/
public void showValue( int arg )
8
9
{
// Object?
10
10
11
12
13
14
15
16
17
18
19
21
// Overridden in subclass
// Can this be called through a subclass
System.out.println("SUPERCLASS: " +
"The int argument was " + arg);
}
/**
This method displays a String.
@param arg A String.
Is showValue “overloaded in this class?
*/
public void showValue( String arg )
22
23 }
24 }
20
{
System.out.println("SUPERCLASS: " +
"The String argument was " + arg);
Code Listing 10-16 (SubClass3.java)
1
2
3
4
5
6
7
8
9
public class SubClass3 extends SuperClass3
{
/**
This method overrides one of the
superclass methods.
@param arg An int.
*/
public void showValue( int
arg )
// <-This May be called thru?
// <-add super.showvalue(arg);
//
AND What is impact?
10 {
11
11
12
13
14
15
16
17
18
19
20
21
22
System.out.println("SUBCLASS: " +
"The int argument was " + arg);
}
/**
This method overloads the superclass
methods.
@param arg A double.
*/
public void showValue( double
{
arg )
// May be called thru?
(Continued)
23
24
25 }
26 }
System.out.println("SUBCLASS: " +
"The double argument was " + arg);
Code Listing 10-17 (ShowValueDemo.java)
1
2
3
4
5
/**
This program demonstrates the methods in the
SuperClass3 and SubClass3 classes.
*/
6
7
public class ShowValueDemo
8
9
10
public static void main(String[] args)
{
{
11
12
SubClass3 myObject = new SubClass3();
13
myObject.showValue( 10 );
// Pass an int.
14
myObject.showValue( 1.2 );
// Pass a double.
THRU A SUBCLASS
// Pass a String.
OBJECT.
15
myObject.showValue( "Hello“ );
16 }
17 }
Program Output
SUBCLASS: The int argument was 10
SUBCLASS: The double argument was 1.2
SUPERCLASS: The String argument was Hello
ALL 3 ARE CALLS
// How would you call
// Superclass method
// showvalue(int arg) ?
See pg. 648(earlier slide)
Code Listing 10-18 (GradedActivity2.java)
1
2
3
4
/**
A class that holds a grade for a graded activity.
*/
5
6
public class GradedActivity2
{
7
8
9
10
11
12
13
protected double score;
14
15
public void setScore(double
{
16
17
18
19
20
21
22
// Numeric score
/**
The setScore method sets the score field.
@param s The value to store in score.
*/
s)
score = s;
}
/**
The getScore method returns the score.
@return The value stored in the score field.
*/
(Continued)
23
24
25
26
27
28
29
30
31
32
33
34
public double getScore()
{
return
score;
}
/**
The getGrade method returns a letter grade
determined from the score field.
@return The letter grade.
*/
35
36
public char getGrade()
{
37
38
39
40
41
42
43
44
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
(Continued)
45
46
47
48
49
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
50
51 }
52 }
return letterGrade;
Code Listing 10-19 (FinalExam2.java)
1
2
3
4
5
6
/**
This class determines the grade for a final exam.
The numeric score is rounded up to the next whole
number if its fractional part is .5 or greater.
*/
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.
18 */
19 //
Constructor Code
19 //----------------------------------------------------------------------------------------------------20 public FinalExam2( int questions, int missed )
21 {
22
double numericScore;
// To hold a numeric score
(Continued)
23
24
// Set the numQuestions and numMissed fields.
25
26
27
28
numQuestions = questions;
numMissed = missed;
29
// Calculate the points for each question and
// the numeric score for this exam.
30
pointsEach = 100.0 / questions;
31
32
numericScore = 100.0 - (missed * pointsEach);
33
// Call the inherited setScore method to
// set the numeric score.
34
setScore( numericScore );
35
36
37
38
39
40
41
42
43
44
// Inherited?
// Adjust the score.
adjustScore();
// Where is method defined?
} //--------------------------------------------------------------------------------------------------/**
The getPointsEach method returns the number of
points each question is worth.
@return The value in the pointsEach field.
(Continued)
45
46
*/
47
48
49
50
51
52
53
54
55
56
57
public double getPointsEach()
{
58
59
60
61
62
63
64
65
66
public int getNumMissed()
{
return pointsEach;
}
/**
The getNumMissed method returns the number of
questions missed.
@return The value in the numMissed field.
*/
return numMissed;
}
/**
The adjustScore method adjusts a numeric score.
If score is within 0.5 points of the next whole
number, it rounds the score up.
(Continued)
67
68
*/
69
private void adjustScore()
// Called from constructor
70
{
// Why is “score” directly available to this
// method?
71
72
double fraction;
73
// Get the fractional part of the score.
74
75
76
fraction = score - (int) score;
77
// If the fractional part is .5 or greater,
// round the score up to the next whole number.
78
if (fraction >= 0.5)
79
score = score + (1.0 - fraction);
80 }
81 } // end class
Code Listing 10-20 (ProtectedDemo.java)
1
2
3
4
5
6
7
import javax.swing.JOptionPane;
8
9
public class ProtectedDemo
10
11
12
/**
This program demonstrates the FinalExam2 class,
which extends the GradedActivity2 class.
*/
{
public static void main(String[] args)
{
String input;
// To hold input
questions;
missed;
13
int
// Number of questions
14
15
16
Int
17
18
input = JOptionPane.showInputDialog("How many " +
19
20
21
questions = Integer.parseInt(input);
22
input = JOptionPane.showInputDialog("How many " +
// Number of questions missed
"questions are on the final exam?");
(Continued)
23
"questions did the student miss?");
24
25
missed = Integer.parseInt(input);
26
// Create a FinalExam object.
27
28
FinalExam2 exam = new FinalExam2( questions, missed );
29
// Display the test results.
30
JOptionPane.showMessageDialog(null,
31
32
"Each question counts " + exam.getPointsEach() +
" points.\nThe exam score is " +
33
exam.getScore() + "\nThe exam grade is " +
exam.getGrade());
34
35
36
37 }
38 }
System.exit(0);
Code Listing 10-21 (PassFailActivity.java)
1
2
3
4
5
/**
This class holds a numeric score and determines
whether the score is passing or failing.
*/
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
16
public PassFailActivity( double mps )
{
17
18
19
20
21
22
minPassingScore = mps;
}
/**
The getGrade method returns a letter grade
determined from the score field. This
(Continued)
23
24
25
26
27
28
29
30
31
method overrides the superclass method.
@return The letter grade.
*/
public char getGrade()
{
char letterGrade;
32
33
34
35
36
37 }
38 }
// OVERRIDES supercalss method
if (super.getScore() >= minPassingScore)
letterGrade = 'P';
else
letterGrade = 'F';
return letterGrade;
Code Listing 10-22 (PassFailExam.java)
1
2
3
4
5
/**
This class determines a passing or failing grade for
an exam.
*/
6
7
8
public class PassFailExam extends PassFailActivity
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
numQuestions;
private double pointsEach;
private int
numMissed;
private int
// Number of questions
// Points for each question
// Number of questions missed
/**
The constructor sets the number of questions, the
number of questions missed, and the minimum passing
score.
@param questions The number of questions.
@param missed The number of questions missed.
@param minPassing The minimum passing score.
*/
public PassFailExam( int questions, int missed,
double minPassing )
(Continued)
23
24
25
26
27
28
29
{
super( minPassing );
/
double numericScore;
30
// Set the numQuestions and numMissed fields.
numQuestions = questions;
numMissed = missed;
31
32
33
34
// Calculate the points for each question and
// the numeric score for this exam.
35
pointsEach = 100.0 / questions;
numericScore = 100.0 - (missed * pointsEach);
36
37
38
39
// Call the superclass's setScore method to
// set the numeric score.
40
41
42
43
44
// Does what? Required?
setScore( numericScore );
}
/**
(Continued)
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
The getPointsEach method returns the number of
points each question is worth.
@return The value in the pointsEach field.
*/
public double getPointsEach()
{
return pointsEach;
}
/**
The getNumMissed method returns the number of
questions missed.
@return The value in the numMissed field.
*/
61 public int getNumMissed()
62 {
63
return numMissed;
64 }
65 }
Code Listing 10-23 (PassFailExamDemo.java)
1
2
3
4
5
6
import java.util.Scanner;
7
8
public class PassFailExamDemo
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
This program demonstrates the PassFailExam class.
*/
{
public static void main(String[] args)
{
int
questions;
missed;
double minPassing
int
// Number of questions
// Number of questions missed
// Minimum passing score
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the number of questions on the exam.
System.out.print("How many questions are " +
"on the exam? ");
questions = keyboard.nextInt();
(Continued)
24
25
26
27
28
29
30
31
32
33
34
36
37
38
39
40
41
42
43
44
System.out.print("How many questions did " +
"the student miss? ");
missed = keyboard.nextInt();
System.out.print("What is the minimum " +
"passing score? ");
minPassing = keyboard.nextDouble();
// Create a PassFailExam object.
PassFailExam exam = new PassFailExam( questions, missed, minPassing );
System.out.println("Each question counts " +
exam.getPointsEach() + " points.");
System.out.println("The exam score is " +
exam.getScore());
(Continued)
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.0
The exam grade is P
Code Listing 10-24 (ObjectMethods.java)
1
2
3
4
5
/**
This program demonstrates the toString and equals
methods that are inherited from the Object class.
*/
6
7
public class ObjectMethods
8
9
10
{
public static void
{
main(String[] args)
11
12
PassFailExam exam1 =
13
14
15
16
18
PassFailExam exam2 =
19
20
21
22
new PassFailExam(0, 0, 0);
new PassFailExam(0, 0, 0);
System.out.println( exam1 );
System.out.println( exam2 );
if (exam1.equals( exam2 ))
//
TESTS What?
(Continued)
23
24
25
26 }
27 }
System.out.println("They are the same.");
else
System.out.println("They are not the same.");
Program Output
PassFailExam@16f0472
PassFailExam@18d107f
They are not the same.
Code Listing 10-25 (Polymorphic.java)
1
/**
2
3
4
This program demonstrates
*/
5
6
public class Polymorphic
7
8
9
polymorphic behavior.
{
public static void main(String[] args)
{
10
11
12
14
GradedActivity[] tests = new GradedActivity[3];
15
16
17
tests[0].setScore(95);
20
tests[1] = new PassFailExam(20, 5, 60); // Why no method call to
// initialize “score”?
21
22
tests[0] = new GradedActivity();
// The third test is the final exam. There were
23
24
25
tests[2] = new FinalExam(50, 7);
26 // Display the grades.
27
28
29
for (int i = 0; i < tests.length; i++)
{
System.out.println("Test " + (i + 1) + ": " +
30
"score " + tests[i].getScore() +
31
32
}
33 }
34 }
Program Output
", grade " + tests[i].getGrade());
Test 1: score 95.0, grade A
Test 2: score 75.0, grade P
Test 3: score 86.0, grade B
//
Why “p” grade?
Code Listing 10-26 (Student.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
The Student class is an abstract class that holds
general data about a student. Classes representing
specific types of students should inherit from
this class.
*/
public abstract class Student
{
private String name;
private String idNumber;
private int yearAdmitted;
// Student name
// Student ID
// Year admitted
/**
The constructor sets the student's name,
ID number, and year admitted.
@param n The student's name.
@param id The student's ID number.
@param year The year the student was admitted.
*/
public Student(String n, String id, int year)
(Continued)
(Continued) Code Listing 10-26 (Student.java)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{
name = n;
idNumber = id;
yearAdmitted = year;
}
/**
The toString method returns a String containing
the student's data.
@return A reference to a String.
*/
public String toString()
{
String str;
str = "Name: " + name
+ "\nID Number: " + idNumber
+ "\nYear Admitted: " + yearAdmitted;
return str;
}
(Continued)
(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 }
Code Listing 10-27 (CompSciStudent.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
This class holds data for a computer science student.
*/
public class CompSciStudent extends Student
{
// Required hours
private final int MATH_HOURS = 20;
// Math hours
private final int CS_HOURS = 40;
// Comp sci hours
private final int GEN_ED_HOURS = 60; // Gen ed hours
// Hours taken
private int mathHours; // Math hours taken
private int csHours;
// Comp sci hours taken
private int genEdHours; // General ed hours taken
/**
The constructor sets the student's name,
ID number, and the year admitted.
@param n The student's name.
@param id The student's ID number.
@param year The year the student was admitted.
(Continued)
(Continued) Code Listing 10-27 (CompSciStudent.java)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
*/
public CompSciStudent(String n, String id, int year)
{
super(n, id, year);
}
/**
The setMathHours method sets the number of
math hours taken.
@param math The math hours taken.
*/
public void setMathHours(int math)
{
mathHours = math;
}
/**
The setCsHours method sets the number of
computer science hours taken.
(Continued)
(Continued) Code Listing 10-27 (CompSciStudent.java)
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@param cs The computer science hours taken.
*/
public void setCsHours(int cs)
{
csHours = cs;
}
/**
The setGenEdHours method sets the number of
general ed hours taken.
@param genEd The general ed hours taken.
*/
public void setGenEdHours(int genEd)
{
genEdHours = genEd;
}
/**
The getRemainingHours method returns the
number of hours remaining to be taken.
(Continued)
(Continued) Code Listing 10-27 (CompSciStudent.java)
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
@return The hours remaining for the student.
*/
public int getRemainingHours()
{
int reqHours,
// Total required hours
remainingHours;
// Remaining hours
// Calculate the required hours.
reqHours = MATH_HOURS + CS_HOURS + GEN_ED_HOURS;
// Calculate the remaining hours.
remainingHours = reqHours - (mathHours + csHours
+ genEdHours);
return remainingHours;
}
/**
The toString method returns a string containing
the student's data.
@return A reference to a String.
(Continued)
(Continued) Code Listing 10-27 (CompSciStudent.java)
89 */
90
91 public String toString()
92 {
93
String str;
94
95
str = super.toString() +
96
"\nMajor: Computer Science" +
97
"\nMath Hours Taken: " + mathHours +
98
"\nComputer Science Hours Taken: " + csHours +
99
"\nGeneral Ed Hours Taken: " + genEdHours;
100
101
return str;
102 }
103 }
Code Listing 10-28 (CompSciStudentDemo.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
This program demonstrates the CompSciStudent class.
*/
public class CompSciStudentDemo
{
public static void main(String[] args)
{
// Create a CompSciStudent object.
CompSciStudent csStudent =
new CompSciStudent("Jennifer Haynes",
"167W98337", 2004);
// Store values for math, CS, and gen ed hours.
csStudent.setMathHours(12);
csStudent.setCsHours(20);
csStudent.setGenEdHours(40);
// Display the student's data.
System.out.println(csStudent);
// Display the number of remaining hours.
(Continued) Code Listing 10-28 (CompSciStudentDemo.java)
23
System.out.println("Hours remaining: " +
24
csStudent.getRemainingHours());
25 }
26 }
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
Code Listing 10-29 (Relatable.java)
1
2
3
4
5
6
7
8
9
10
/**
Relatable interface
*/
public interface Relatable
{
boolean equals(GradedActivity g);
boolean isGreater(GradedActivity g);
boolean isLess(GradedActivity g);
}
Code Listing 10-30 (FinalExam3.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
This class determines the grade for a final exam.
*/
public class FinalExam3 extends GradedActivity
implements Relatable
{
private int numQuestions;
// Number of questions
private double pointsEach;
// Points for each question
private int numMissed;
// Questions missed
/**
The constructor sets the number of questions on the
exam and the number of questions missed.
@param questions The number of questions.
@param missed The number of questions missed.
*/
public FinalExam3(int questions, int missed)
{
double numericScore;
// To hold a numeric score
(Continued)
(Continued) Code Listing 10-30 (FinalExam3.java)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Set the numQuestions and numMissed fields.
numQuestions = questions;
numMissed = missed;
// Calculate the points for each question and
// the numeric score for this exam.
pointsEach = 100.0 / questions;
numericScore = 100.0 - (missed * pointsEach);
// Call the inherited setScore method to
// set the numeric score.
setScore(numericScore);
}
/**
The getPointsEach method returns the number of
points each question is worth.
@return The value in the pointsEach field.
*/
public double getPointsEach()
{
(Continued)
(Continued) Code Listing 10-30 (FinalExam3.java)
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
return pointsEach;
}
/**
The getNumMissed method returns the number of
questions missed.
@return The value in the numMissed field.
*/
public int getNumMissed()
{
return numMissed;
}
/**
The equals method compares the calling object
to the argument object for equality.
@return true if the calling
object's score is equal to the argument's
score.
*/
(Continued)
(Continued) Code Listing 10-30 (FinalExam3.java)
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
public boolean equals(GradedActivity g)
{
boolean status;
if (this.getScore() == g.getScore())
status = true;
else
status = false;
return status;
}
/**
The isGreater method determines whether the calling
object is greater than the argument object.
@return true if the calling object's score is
greater than the argument object's score.
*/
public boolean isGreater(GradedActivity g)
{
boolean status;
(Continued)
(Continued) Code Listing 10-30 (FinalExam3.java)
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
if (this.getScore() > g.getScore())
status = true;
else
status = false;
return status;
}
/**
The isLess method determines whether the calling
object is less than the argument object.
@return true if the calling object's score is
less than the argument object's score.
*/
public boolean isLess(GradedActivity g)
{
boolean status;
if (this.getScore() < g.getScore())
status = true;
(Continued)
(Continued) Code Listing 10-30 (FinalExam3.java)
111
112
113
114
115 }
116 }
else
status = false;
return status;
Code Listing 10-31 (InterfaceDemo.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
This program demonstrates the FinalExam3 class, which
implements the Relatable interface.
*/
public class InterfaceDemo
{
public static void main(String[] args)
{
// Exam #1 had 100 questions and the student
// missed 20 questions.
FinalExam3 exam1 = new FinalExam3(100, 20);
// Exam #2 had 100 questions and the student
// missed 30 questions.
FinalExam3 exam2 = new FinalExam3(100, 30);
// Display the exam scores.
System.out.println("Exam 1: " +
exam1.getScore());
System.out.println("Exam 2: " +
exam2.getScore());
(Continued)
(Continued) Code Listing 10-31 (InterfaceDemo.java)
23
24
// Compare the exam scores.
25
if (exam1.equals(exam2))
26
System.out.println("The exam scores " +
27
"are equal.");
28
29
if (exam1.isGreater(exam2))
30
System.out.println("The Exam 1 score " +
31
"is the highest.");
32
33
if (exam1.isLess(exam2))
34
System.out.println("The Exam 1 score " +
35
"is the lowest.");
36 }
37 }
Program Output
Exam 1: 80.0
Exam 2: 70.0
The Exam 1 score is the highest.
Code Listing 10-32 (RetailItem.java)
1
2
3
4
5
6
7
8
/**
RetailItem interface
*/
public interface RetailItem
{
public double getRetailPrice();
}
Code Listing 10-33 (CompactDisc.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
Compact Disc class
*/
public class CompactDisc implements RetailItem
{
private String title;
// The CD's title
private String artist;
// The CD's artist
private double retailPrice;
// The CD's retail price
/**
Constructor
@param cdTitle The CD title.
@param cdArtist The name of the artist.
@param cdPrice The CD's price.
*/
public CompactDisc(String cdTitle, String cdArtist,
double cdPrice)
{
title = cdTitle;
artist = cdArtist;
(Continued)
(Continued) Code Listing 10-33 (CompactDisc.java)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
retailPrice = cdPrice;
}
/**
getTitle method
@return The CD's title.
*/
public String getTitle()
{
return title;
}
/**
getArtist method
@return The name of the artist.
*/
public String getArtist()
{
return artist;
}
(Continued)
(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 }
Code Listing 10-34 (DvdMovie.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
DvdMovie class
*/
public class DvdMovie implements RetailItem
{
private String title;
// The DVD's title
private int runningTime;
// Running time in minutes
private double retailPrice;
// The DVD's retail price
/**
Constructor
@param dvdTitle The DVD title.
@param runTime The running time in minutes.
@param dvdPrice The DVD's price.
*/
public DvdMovie(String dvdTitle, int runTime,
double dvdPrice)
{
title = dvdTitle;
runningTime = runTime;
(Continued)
(Continued) Code Listing 10-34 (DvdMovie.java)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
retailPrice = dvdPrice;
}
/**
getTitle method
@return The DVD's title.
*/
public String getTitle()
{
return title;
}
/**
getRunningTime method
@return The running time in minutes.
*/
public int getRunningTime()
{
return runningTime;
}
(Continued)
(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 }
Code Listing 10-35 (PolymorphicInterfaceDemo.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
This program demonstrates that an interface type may
be used to create a polymorphic reference.
*/
public class PolymorphicInterfaceDemo
{
public static void main(String[] args)
{
// Create a CompactDisc object.
CompactDisc cd =
new CompactDisc("Greatest Hits",
"Joe Looney Band",
18.95);
// Create a DvdMovie object.
DvdMovie movie =
new DvdMovie("Wheels of Fury",
137, 12.95);
// Display the CD's title.
System.out.println("Item #1: " +
cd.getTitle());
(Continued)
(Continued) Code Listing 10-35 (PolymorphicInterfaceDemo.java)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Display the CD's price.
showPrice(cd);
// Display the DVD's title.
System.out.println("Item #2: " +
movie.getTitle());
// Display the DVD's price.
showPrice(movie);
}
/**
The showPrice method displays the price
of a RetailItem object.
@param item A reference to a RetailItem object.
*/
private static void showPrice(RetailItem item)
{
System.out.printf("Price: $%,.2f\n", item.getRetailPrice());
}
(Continued)
(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