Chapter 13

85
1 Chapter 13 Inheritance, interface and Polymorphism

description

Chapter 13. Inheritance , interface and Polymorphism. Chapter 13 Objectives. Understanding inheritance and polymorphism. Write programs that are easily extensible and modifiable by applying polymorphism in program design. - PowerPoint PPT Presentation

Transcript of Chapter 13

Page 1: Chapter 13

1

Chapter 13

Inheritance, interface and Polymorphism

Page 2: Chapter 13

2

Chapter 13 Objectives

• Understanding inheritance and polymorphism.– Write programs that are easily extensible and modifiable by

applying polymorphism in program design.

• Define reusable classes based on inheritance and abstract classes and abstract methods.

• understand and know how to use all java visibility modifiers– private, package, protected, public.

• Understand java interfaces• Differentiate the abstract classes and Java interfaces.

Page 3: Chapter 13

32

Inheritance

• Inheritance allows a software developer to derive a new class from an existing one

• The existing class is called the parent class, or superclass, or base class

• The derived class is called the child class or subclass.• The child class inherits characteristics (data &

methods) of the parent class– That is, the child class inherits the methods and fields

defined for the parent class

Page 4: Chapter 13

4

Defining Classes with Inheritance

• Case Study:– Implement a class roster that contains both

undergraduate and graduate students.– Each student’s record will contain

• his or her name, • three test scores, and • the final course grade.

– The formula for determining the course grade is different for graduate students than for undergraduate students.

Page 5: Chapter 13

5

Modeling Two Types of Students

• Two possible ways to design the classes:– Define two unrelated classes, one for

undergraduates and one for graduates.– Define three classes, one (superclass) for the

common part of both kinds of students, and one (subclass) for either kind of students. Either subclass need only describe those parts of the kind of students it describes which were not described in the common part class. --- Programming by difference

Page 6: Chapter 13

6

Classes for the Class Roster

• For the Class Roster sample, we design three classes:– Student– UndergraduateStudent– GraduateStudent

• The Student class will incorporate behavior and data common to both UndergraduateStudent and GraduateStudent objects.

• The UndergraduateStudent class and the GraduateStudent class will each contain behaviors and data specific to their respective objects.

Page 7: Chapter 13

7

Inheritance Hierarchy

Page 8: Chapter 13

8

Class Hierarchies (Further Example )

• A child class of one parent can be the parent of another child, forming class hierarchies

Animal

Mammal Bird

Horse Bat Parrot

Page 9: Chapter 13

913

The Object Class

• A class called Object is defined in the java.lang package, – All objects are derived from the Object class– If a class is not explicitly defined to be the child of an

existing class, it is assumed to be the child of the Object class

– The Object class is therefore the ultimate root of all class hierarchies

• The Object class contains a few useful methods, such as toString(),equals(), hashCode() which are inherited by all classes.

• You may choose to override equals and/or toString to define equality/toString in your way.

Page 10: Chapter 13

10

Single vs. Multiple Inheritance

• Java supports single inheritance, meaning that a child class can have only one parent class

• Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents

• Collisions, such as the same variable name in two parents, have to be resolved

• In most cases, the use of interfaces gives us the best aspects of multiple inheritance without the overhead.

Page 11: Chapter 13

11

The Protected Modifier

• The modifier protected makes a data member or method visible and accessible to – the class where the member is defined and– the descendant classes

Page 12: Chapter 13

12

Visibility modifiers and their usage

The visibility modifiers determine which class members can be referenced from where and which cannot.

• public members:– all classes

• protected members– all classes in the same package +– all subclasses (and subsubclasses …)– Note: Java has no notions of public, private or protected inheritance as in C++; all

inheritances are public.• package members [default visibility]

– all classes in the same package• private members

– can only be used in the same class where the member is defined.

Page 13: Chapter 13

13

package a.b.c;public class A {public int p1…protected int p2…int p4; //package scopeprivate int p3 … }

extend A extend A extend A

visible region for package members

visible region for protected members

visible region for pubic members [of class A]

Visible regions for members of class A

package a.b.c

package a.b.c… extend A

visible region forprivate membersof class A

package a.b.c

Page 14: Chapter 13

14

Inheritance and Member Accessibility

• We use the following visual representation of inheritance to illustrate data member accessibility.

Page 15: Chapter 13

15

The Effect of Three Visibility Modifiers

Page 16: Chapter 13

16

Accessibility of Super from Sub

• Everything except the private members of the Super class is visible from a method of the Sub class.

Page 17: Chapter 13

17

Kinds of APIs

• Application Programming Interface (API )• Client’s API

– see only public classes and class members

• Developer’s API– client’s API + protected class/class members

• Implementer or hacker’s API– See all.– Developer’s API + private/package class/members.

Page 18: Chapter 13

18

Types of Objects and Variables• The (actual) type of an object is the class that is referred to when it

is created via the “new” operation.– Student s1 = new Student(“name”, age, sex);

• Two types associated with variables ( including method parameters/fields):– The declared type of a variable is the type referred to in its declaration (also:

declared class; compile-time type) – Person p1, p2 = new Person(…) ;– The actual type of a variable is the type of the object bound to the variable at

a specific moment during program execution (also: run-time type)– p1 = s1 ; – Note: the declared type of a variable is static(i.e., unchangable ) once it is

declared, while the actual type of a variable is dynamic (i.e., can be changed and known until runtime).

– p2 = s1;

Page 19: Chapter 13

19

Example: Declared type and actual type

Page 20: Chapter 13

20

Example: Actual type

•A variable can have multiple actual types during its life time •A variable’s actual types can be known until runtime.

Page 21: Chapter 13

218

Signature of a method or constructor• The signature of a method or constructor:

… returnTypeopt m(Type1 arg1,…, Typen argn) throws Exception1,…,Exceptionm { … }

is the list [m, Type1, …, Typen]• Notes: return type, parameter name and exceptions

are not part of method signature.

Page 22: Chapter 13

22

Redefinitions of methods/constructors in subclass

• We say an instance method m1 (or constructor) of a super class P is overridden by an instance method m2 (or constructor) of a child class C iff– m1 and m2 have the same signature,– m1 is not private (nor static),– m2 has the same or more open visibility.

• notes: – public(+) > protected(#) > package (default)– It is illegal that m2 less visibile than m1.– (e.g., m1 is + but m2 is #).

# int m1()

int f1 ;

SuperClass

+ int m1()

int f1 ;

SubClass

Page 23: Chapter 13

23

Examples

SuperClass

- int m1()

SubClass

#/+/d/- int m1()

SuperClass

# int m1(int a)

SubClass1

#/+ int m1(int t)

SubClass2

-/d long m1(int a)

(x ;illegal)

(two mistakes here)

Page 24: Chapter 13

24

Redefinitions of fields in subclass

• We say an instance field f1 (or constructor) of a super class P is shadowed by an instance field f2 of a child class C iff– m1 and m2 have the same name,– m1 is not private (nor static),

• notes: – Essentially there is no restriction on– fields with the same name.– It is legal that m2 less visibile than m1.– It is also legal that m1 and m2 – have different types

SuperClass

+int f1 ;

# int m1()

SubClass

# long f1 ;

# int m1()

Page 25: Chapter 13

25

Examples

SuperClass

- int f

SubClass

#/+/d/- int f

SuperClass

# int f

SubClass1

#/+ int f

SubClass2

-/d long f

(0 ;illegal)

(No mistake here)

Page 26: Chapter 13

26

Overriding and Shadowing handling

• What happens if both parent and child class contains members of the same name or signature ?– fields => variable shadowing;– constructor => impossible!– methods => methods overriding

Page 27: Chapter 13

27

Method Overriding (continued)

• The actual type (not casted type) of an object determines which method is invoked

• This mechanism : (– variables enabling different actual types + – actual type determine which method is invoked

) is called polymorphism.

Page 28: Chapter 13

28

Polymorphism Example

• Java allows a single variable to refer to objects of different subtypes of the declared type of the variable.

• For example, if Cat and Dog are subclasses of Pet, then the following statements are valid:

Pet myPet; // declared type

myPet = new Dog(); // actual type

. . .

myPet = new Cat();

• Actual type must be the declared type or a subtype of the declared type.

Page 29: Chapter 13

29

Creating the roster Array

• We can maintain our class roster using an array, combining objects from the Student, UndergraduateStudent, and GraduateStudent classes.

Student roster = new Student[40];

. . .

roster[0] = new GraduateStudent();

roster[1] = new UndergraduateStudent();

roster[2] = new UndergraduateStudent();

. . .

Page 30: Chapter 13

30

State of the roster Array

• The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes.

Page 31: Chapter 13

31

Sample Polymorphic Message• To compute the course grade using the roster array, we execute

• If student refers to a GraduateStudent, then the computeCourseGrade method of the GraduateStudent class is executed.

• If student refers to an UndergraduateStudent, then the computeCourseGrade method of the UndergraduateStudent class is executed.

• Note: It is the actual type (a runtime property) instead of declared type that determines which method to be executed.

for (Student student : roster ) {

student.computeCourseGrade();

}

Page 32: Chapter 13

32

The instanceof Operator

• The instanceof operator can help us learn the class (actual type) of an object.

• The following code counts the number of undergraduate students.

int undergradCount = 0;

for (int i = 0; i < numberOfStudents; i++) {

if(roster[i] instanceof UndergraduateStudent)

{ undergradCount++; }

}

Page 33: Chapter 13

33

class Messages { public static void main (String[] args) { Message m = new Message(); Advice a = new Advice(); m.message(); a.message(); (Message a).message() // same as a.message() } } // class Messages

class Message { public void message() { System.out.println (”Message"); } } // class Thought

class Advice extends Message { public void message() { // overriding method System.out.println (”Advice"); } } // class Advice

More Example

Page 34: Chapter 13

349

Overloading vs. Overriding

• Don‘t confuse the concepts of overloading (多載 ) and overriding(覆蓋 )

• Overloading deals with multiple methods in the same class with the same name but different signatures

• Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature

• Overloading lets you define a similar operation in different ways for different data

• Overriding lets you define a similar operation in different ways for different object types

Page 35: Chapter 13

35

Inheritance and Constructors

• Constructors of a superclass are not inherited by its subclasses.– You must define a constructor for a class or – use the default constructor public <className>() {} added by the compiler.

• The statement

super(...);can be used to call the superclass’s constructor.– use it to reuse super class’s constructs.– must be the first statement in the body.

• No “extends’ clause used, then superclass is assumed to be the Object class.

… class A { …} means … class A extends Object {…}

Page 36: Chapter 13

36

Example

public class Circle{ public double x, y, r; // instance variables // ncircles is class variable public static int ncircles = 0; // Constructors public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; ncircles++; } public Circle(double r) { this(0.0,0.0, r ) ; ncircles++; } ...}

Page 37: Chapter 13

37

Subclass Example• The class GraphicCircle:

public class GraphicCircle extends Circle { // Extra fields

Color outline, fill;

// Extra constructors

public GraphicCircle(Color edge, Color fill)

{ x = 0.0; y = 0.0; r = 1.0;

outline = edge; this.fill = fill; }

public GraphicCircle(double r, Color edge, Color fill)

{ super(r); outline = edge; this.fill = fill; }

// Extra methods

public void draw(Graphics g)

{ g.setColor(outline); g.drawOval(x-r, y-r, 2*r, 2*r);

g.setColor(fill); g.fillOval(x-r, y-r, 2*r, 2*r); }

}

Page 38: Chapter 13

3810

The super Reference Revisited

• Inherited parent methods/fields can be explicitly invoked using the super reference

• If a method is declared with the final modifier, it cannot be overridden– c.f: a final field cannot be modified!.

• The concept of overriding can be applied to data (called shadowing variables), but shadowing behaves quite differently from overriding.

• The syntax of super is: super.method (parameters) super.var

Page 39: Chapter 13

39

Shadowing superclass fields vs overriding superclass methods

class A { int x ; int m() …}class B extends A { int x; int m() …}class C extends B { int x; // x in B and A are shadowed // by this.x int m() {…} // m() overrides m() in A & B C c = new C(); … x, this.x // field x in C super.x, ((B) this).x // field x in B ((A) this).x // filed x in A super.super.x // syntax error!! c.x // field in C((B)c).x // fields in B((A)c).x // fields in A

((A) c).m() ; // m() in A ? no !!super.m(); // m() in B((B) this).m(); // m() in C((A) this).m(); // m() in C((A) c).m();((B) c).m();m(); // m() in C

Page 40: Chapter 13

40

class Firm { public static void main (String[] args) { Manager sam = new Manager ("Sam", "123 Main Line", "555-0469", "123-45-6789", 1923.07); Employee carla = new Employee ("Carla", "456 Off Line", "555-0101", "987-65-4321", 846.15); Employee woody = new Employee ("Woody", "789 Off Rocker", "555-0000", "010-20-3040", 769.23); woody.print(); out.println ("Paid: " + woody.pay()); System.out.println(); carla.print(); out.println ("Paid: " + carla.pay()); System.out.println(); sam.print(); sam.awardBonus (2000); out.println ("Paid: " + sam.pay()); System.out.println(); } }

Page 41: Chapter 13

41

class Employee { protected String name, address, phone, ID; protected double salary; public Employee (String name, String address, String phone, String ID, double salary) { this.name = name; this.address = address; this.phone = phone; this.payRate = payRate; this.ID = ID; } // constructor Employee public double pay () { return salary; } // method pay public void print () { System.out.println (name + " " + ID); System.out.println (address); System.out.println (phone); } } // class Employee

Page 42: Chapter 13

42

class Manager extends Employee { private double bonus; public Manager (String name, String address, String phone, String ID, double pay) { super (name, nddress, phone, ID, pay); // call parent’s constructor bonus = 0; // bonus yet to be awarded } public void awardBonus (double bonus) { this.bonus = bonus; } public double pay () { // managers need special way to count pay! double pay = super.pay() + bonus; // call parent’s method bonus = 0; return pay; } }

Page 43: Chapter 13

43

Abstract Superclasses and Abstract Methods

• When we define a superclass, we often do not need to create any instances of the superclass.– We want use instances of its subclasses only.– Ex: class Shape { – double area() ; – double cricumference(); … – }– class Rectangle extends Shape {…}– class Ellipse extends Shape { … }

• Depending on whether we need to create instances of the superclass, we must define the class differently.

Page 44: Chapter 13

44

Definition: Abstract Class

• An abstract method is a method with the keyword abstract, and it ends with a semicolon instead of a method body.– Private methods and static methods may not be declared abstract.

• An abstract class is a class which is defined with the modifier abstract and/or– contains zero or more abstract methods OR– that does not provide an implementation of an inherited

abstract method.• No instances can be created from an abstract class.

– If A in an abstract class, then it is illegal to use new A(…).

Page 45: Chapter 13

45

Abstract Classes revisted

• An abstract class is a placeholder in a class hierarchy that represents a generic concept

• An abstract class cannot be instantiated

• We use the modifier abstract on the class header to declare a class as abstract

• An abstract class often contains abstract methods (like an interface does), though it doesn’t have to

Page 46: Chapter 13

46

Abstract Classes

• The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract

• An abstract method cannot be defined as final (because it must be overridden) or static (because it has no definition yet)

• The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate

Page 47: Chapter 13

47

Case 1

• Student Must Be Undergraduate or Graduate

– If a student must be either an undergraduate or a graduate student, we only need instances of UndergraduateStudent or GraduateStudent.

– Therefore, we must define the Student class so that no instances may be created of it.

Page 48: Chapter 13

48

Case 2

• Student Does Not Have to Be Undergraduate or Graduate.

• In this case, we may design the Student class in one of two ways.– We can make the Student class instantiable. – We can leave the Student class abstract and add a third

subclass, OtherStudent, to handle a student who does not fall into the UndergraduateStudent or GraduateStudent categories.

Page 49: Chapter 13

49

Which Approach to Use

• The best approach depends on the particular situation.

• When considering design options, we can ask ourselves which approach allows easier modification and extension.

Page 50: Chapter 13

50

Interfaces

• A Java interface is a collection of abstract methods and constants

• An abstract method is a method header without a method body (i.e., no implementation)

• An abstract method in an interface can be declared using the modifier abstract, but because all methods in an interface are abstract, it is usually left off.– cf: abstract methods in an abstract class must be declared explicitly

using the abstract modifier.• An interface is used to formally define a set of methods that a

class will implement

Page 51: Chapter 13

51

Inheritance versus Interface

• Java interface – used to share common behavior (only method headers) among

the instances of different classes.

• Inheritance – used to share common code (including both data members and

methods) among the instances of related classes.

• In your program designs, remember to use the Java interface to share common behavior. Use inheritance to share common code.

• If an entity A is a specialized form of another entity B, then model them by using inheritance. Declare A as a subclass of B.

Page 52: Chapter 13

52

Interfaces

public interface Doable{ public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num);}

interface is a reserved wordNone of the methods in anNone of the methods in an

interface are giveninterface are givena definition (body)a definition (body)

A semicolon immediatelyA semicolon immediatelyfollows each method headerfollows each method header

Page 53: Chapter 13

53

Interfaces

• An interface cannot be instantiated– Doable d = new Doable(); // error

• Like a class, a user-defined interface can be used as the type of variables.– Doable a, b;

• Methods in an interface have public visibility by default

• A class formally implements an interface by– stating so in the class header– providing implementations for each abstract method in the interface

• If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will produce errors.

Page 54: Chapter 13

54

Interfaces

public class CanDo implements Doable{ public void doThis () { // whatever }

public void doThat () { // whatever }

// etc.}

implements is aimplements is areserved wordreserved word

Each method listedEach method listedin Doable isin Doable is

given a definitiongiven a definition

Page 55: Chapter 13

55

Interfaces

• A class can implement more than one interfaces• The interfaces are listed in the implements clause,

separated by commasclass cName extends superClass implements If1,…Ifn {

… }

• The class must implement all methods in all interfaces listed in the header– O/W, It must declare itself as an abstract class.

Page 56: Chapter 13

569

Interfaces

• An interface can be implemented by multiple classes

• Each implementing class can provide their own unique version of the method definitions

• An interface is not part of the class hierarchy• A class can be derived from a base class and

implement one or more interfaces

Page 57: Chapter 13

5710

Interface constants

• Unlike interface methods, interface constants require nothing special of the implementing class

• Constants in an interface can be used in the implementing class as if they were declared locally

• This feature provides a convenient technique for distributing common constant values among multiple classes

Page 58: Chapter 13

5811

Extending Interfaces

• An interface can be derived from another interface, using the extends reserved word

• The child interface inherits the constants and abstract methods of the parent

• Note that the interface hierarchy and the class hierarchy are distinct

• Unlike class hierarchy, an interface can extend more than one interfaces.– public interface Transformable extends Scable, Translatable,

Rotatable { }

• A class that implements an interface must define also all methods in all ancestors of the interface.

Page 59: Chapter 13

59

interface Printable { public String name(); public String print(); // public can be omitted} // interface Printable

class PrintLogger { public void log (Printable file) { System.out.println (file.name() + " : " + file.print()); } // method log} // class PrintLogger

An interface Example

Page 60: Chapter 13

60

class File { protected String id; protected int size; public File (String id, int size) { this.id = id; this.size = size; } // constructor File public String name() { return id; } // method name} // class Fileclass TextFile extends File implements Printable { protected String text; public TextFile (String id, int size, String contents) { super(id, size); text = contents; } // constructor TextFile public String print() { return text; } } // class TextFile

Page 61: Chapter 13

61

class BinaryFile extends File { protected byte[] data; public BinaryFile (String id, int size, byte[] data) { super(id, size); this.data = data; } // constructor BinaryFile} // class BinaryFile

class ImageFile extends BinaryFile implements Printable { public ImageFile (String id, int size, byte[] data) { super(id, size, data); } // constructor ImageFile public String print() { return new String (data); } } // class Image_File

Page 62: Chapter 13

62

public class Printer { public static void main (String[] args) { byte[] logoData = {41, 42, 49, 44 };

TextFile report = new TextFile (“Reprot 1", 1024, "One two three …");

ImageFile logo = new ImageFile(“Picture 1", 4, logoData); PrintLogger daily = new PrintLogger(); daily.log (report); daily.log (logo); }}

Page 63: Chapter 13

63

Marker interface

• An interface without including any method.– useful for providing additional information about an object.– EX:– java.lang.Serializable– java.lang.Cloneable– java.rmi.Remote

Ex:

Object obj;Object copy;copy = o.clone() // may raise CloneNotSupportedExceptionexceptionif(obj instanceof Cloneable) copy = o.clone();else copy = null;

Page 64: Chapter 13

64

Polymorphism via Interfaces

• An interface name can be used as the type of an object reference variable

Doable obj;

• The obj reference can be used to point to any object of any class that implements the Doable interface

• The version of doThis that the following line invokes depends on the type of object that obj is referring to:

obj.doThis();

Page 65: Chapter 13

65

Polymorphism via Interfaces

Doable obj ;• The reference obj is polymorphic, which means it can

have many forms.

• That line of code “ obj.DoThis() “ might execute different methods at different times if the object that obj points to changes

• Note that polymorphic references must be resolved at run time; this is called dynamic binding

• Careful use of polymorphic references can lead to elegant, robust software designs

Page 66: Chapter 13

66

Some interfaces used in core java classes

• The Java standard class library contains many interfaces that are helpful in certain situations

• The Comparable interface contains an abstract method called compareTo, which is used to compare two objects

pubilc iterface Comparable { public abstract int comparedTo(Object); }Ex: int rlt = x.comparedTo(y); if(rlt < 0) {… } // x < y else if (rlt>0) { …} // x > y else {…} // rlt = 0 means x is equal to y.• The String class implements Comparable which gives us the ability to put

strings in alphabetical order

Page 67: Chapter 13

67

The Iterator and Enumeration interface

The java.util.Iterator/Enumeration interface contain methods that allow the user to move through a collection of objects easilypublic interface Iterator { public abstract boolean hasNext(); public abstract Object next(); public abstract void remove(); }pubic interface Enumeration { public boolean hasMoreElements(); pubic Object nextElement(); }

Ex: Object obj ; // obj is an object implementing Iterator for(Iterator i = (Iterator)obj; i.hasNext(); ) processing(i.next());

Page 68: Chapter 13

68

Problem Statement

• Problem statement:Write an application that reads in a text file organized in the manner shown below and displays the final course grades.The course grades are computed differently for the undergraduate and graduate students based on the formulas listed on page 710. The input text file format is as follows:

• A single line is used for information on one student.

• Each line uses the format

<Type> <Name> <Test 1> <Test 2> <Test 3>

where

<Type> designates either a graduate or an undergraduate student,

<Name> designates the student’s first and last name, and

<Test i> designates the ith test score.

• End of input is designated by the word END. The case of the letters is

insignificant.

Page 69: Chapter 13

69

Overall Plan

• Tasks1. Read an input text file.2. Compute the course grades.3. Print out the result.

• Input File Format

Page 70: Chapter 13

70

Development Steps

• We will develop this program in five steps:

1. Start with the program skeleton.Define the skeleton ComputeGrades classes.

2. Implement the printResult method.Define any other methods necessary to implement printResult.

3. Implement the computeGrade method.Define any other methods necessary to implement computeGrade.

4. Implement the readData method.Define any other methods necessary to implement readData.

5. Finalize and look for improvements.

Page 71: Chapter 13

71

Step 1 Design

• We start with a program skeleton.• We will define two constructors so the programmer

can create a roster of default size or the size of her choice.

Page 72: Chapter 13

72

Step 1 Code

Directory: Chapter13/Step1

Source Files: ComputeGrades.java

Directory: Chapter13/Step1

Source Files: ComputeGrades.java

Program source file is too big to list here. From now on, we askyou to view the source files using your Java IDE.

Page 73: Chapter 13

73

Step 1 Test

• We include a temporary output statement inside the (currently stub) method we define.

• We run the test main class and verify that the methods are called correctly.

Page 74: Chapter 13

74

Step 2 Design

• We design and implement the printResult method

• We use the helper class OutputBox for displaying the result.

for each element i in the roster array {

output the name of roster[i];

output the test scores of roster[i];

output the course grade of roster[i];

skip to the next line;

}

Page 75: Chapter 13

75

Step 2 Code

Directory: Chapter13/Step2

Source Files: ComputeGrades.java

Directory: Chapter13/Step2

Source Files: ComputeGrades.java

Page 76: Chapter 13

76

Step 2 Test

• We verify the temporary readData method is working correctly. This confirms that we are using the correct student classes and using their methods correctly.

• We verify the printResult method does indeed display the data in our desired format.

Page 77: Chapter 13

77

Step 3 Design

• We design and implement the computeGrade method.

• The code for actually determining the course grade is embedded in individual student classes – So the code to add to the ComputeGrades class is very

simplistic.– This is a direct benefit of using polymorphism

effectively.

Page 78: Chapter 13

78

Step 3 Code

Directory: Chapter13/Step3

Source Files: ComputeGrades.java

Directory: Chapter13/Step3

Source Files: ComputeGrades.java

Page 79: Chapter 13

79

Step 3 Test

• We will repeat the same test routines from Step 2. • Instead of seeing four asterisks, we should be seeing the

correct grades.• We test both the passing and not passing test scores.

Page 80: Chapter 13

80

Step 4 Design

• We design and implement the core functionality of the program—the readData method

• We can express its logic as

get the filename from the user;

if (the filename is provided)

read in data and build the roster array;

else

output an error message;

Page 81: Chapter 13

81

The buildRoster Method

• The logic of the workhorse private method buildRoster is as follows:

set bufReader for input;

while ( !done ) {

line = get next line;

if (line is END) {

done = true;

} else {

student = createStudent( line );

if (student != null) {

roster[studentCount] = student; //add to roster

studentCount++;

}

}

Page 82: Chapter 13

82

The createStudent Method• We use the StringTokenizer class to break down items in a single

line of input

StringTokenizer parser = new StringTokenizer( line );

String type;

try {

type = parser.nextToken();

if (type.equals(UNDER_GRAD) || type.equals(GRAD)) {

student = newStudentWithData(type, parser);

} else { //invalid type is encountered

student = null;

}

} catch (NoSuchElementException e) { //no token

student = null;

}

return student;

Page 83: Chapter 13

83

Step 4 Code

Directory: Chapter13/Step4

Source Files: ComputeGrades.java

Directory: Chapter13/Step4

Source Files: ComputeGrades.java

Page 84: Chapter 13

84

Step 4 Test

• We run through a more complete testing routine in this step.We need to run the program for various types of input files. Some of the possible file contents are as follows:

Page 85: Chapter 13

85

Step 5: Finalize and Improve

• We finalize the program by correcting any remaining errors, inconsistency, or unfinished methods.

• We want to review the methods and improve them as necessarily.

• One problem (which would have been identified in step 4 testing) we need to correct is the missing method for expanding the roster array when the input file includes more student entries than the set default size of 25.– We leave this method as Exercise 3. – We also leave some of the possible improvements as exercises.