Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to OOP with Java, C. Thomas Wu

Similar presentations


Presentation on theme: "Intro to OOP with Java, C. Thomas Wu"— Presentation transcript:

1 Intro to OOP with Java, C. Thomas Wu
Chapter 13 Inheritance, interface and Polymorphism ©The McGraw-Hill Companies, Inc.

2 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

3 Intro to OOP with Java, C. Thomas Wu
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 2 ©The McGraw-Hill Companies, Inc.

4 Defining Classes with Inheritance
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.

5 Modeling Two Types of Students
Intro to OOP with Java, C. Thomas Wu 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 ©The McGraw-Hill Companies, Inc.

6 Classes for the Class Roster
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.

7 Inheritance Hierarchy
Intro to OOP with Java, C. Thomas Wu Inheritance Hierarchy ©The McGraw-Hill Companies, Inc.

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

9 Intro to OOP with Java, C. Thomas Wu
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. 13 ©The McGraw-Hill Companies, Inc.

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.

11 The Protected Modifier
Intro to OOP with Java, C. Thomas Wu 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 ©The McGraw-Hill Companies, Inc.

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.

13 Visible regions for members of class A
visible region for pubic members [of class A] visible region for protected members package a.b.c visible region for package members package a.b.c; public class A { public int p1… protected int p2… int p4; //package scope private int p3 … } package a.b.c package a.b.c … extend A visible region for private members of class A extend A extend A extend A

14 Inheritance and Member Accessibility
Intro to OOP with Java, C. Thomas Wu Inheritance and Member Accessibility We use the following visual representation of inheritance to illustrate data member accessibility. ©The McGraw-Hill Companies, Inc.

15 The Effect of Three Visibility Modifiers
Intro to OOP with Java, C. Thomas Wu The Effect of Three Visibility Modifiers ©The McGraw-Hill Companies, Inc.

16 Accessibility of Super from Sub
Intro to OOP with Java, C. Thomas Wu Accessibility of Super from Sub Everything except the private members of the Super class is visible from a method of the Sub class. ©The McGraw-Hill Companies, Inc.

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.

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;

19 Example: Declared type and actual type

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.

21 Signature of a method or constructor
Intro to OOP with Java, C. Thomas Wu 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. 8 ©The McGraw-Hill Companies, Inc.

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() SubClass

23 Examples SuperClass SuperClass - int m1() # int m1(int a) SubClass1
(x ;illegal) SubClass1 #/+ int m1(int t) SubClass #/+/d/- int m1() SubClass2 -/d long m1(int a) (two mistakes here)

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()

25 Examples SuperClass SuperClass - int f # int f SubClass1 SubClass
(0 ;illegal) SubClass1 #/+ int f SubClass #/+/d/- int f SubClass2 -/d long f (No mistake here)

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

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.

28 Intro to OOP with Java, C. Thomas Wu
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(); A variable of class X may not refer to an object from the superclass or sibling classes of X. Sibling classes are those that share the common ancestor class. For example, the following statements are invalid: Dog myDog = new Cat(); Cat myCat = new Pet(); Actual type must be the declared type or a subtype of the declared type. ©The McGraw-Hill Companies, Inc.

29 Creating the roster Array
Intro to OOP with Java, C. Thomas Wu 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(); ©The McGraw-Hill Companies, Inc.

30 State of the roster Array
Intro to OOP with Java, C. Thomas Wu State of the roster Array The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes. ©The McGraw-Hill Companies, Inc.

31 Sample Polymorphic Message
Intro to OOP with Java, C. Thomas Wu 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(); } ©The McGraw-Hill Companies, Inc.

32 The instanceof Operator
Intro to OOP with Java, C. Thomas Wu 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++; } } ©The McGraw-Hill Companies, Inc.

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

34 Overloading vs. Overriding
Intro to OOP with Java, C. Thomas Wu 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 9 ©The McGraw-Hill Companies, Inc.

35 Inheritance and Constructors
Intro to OOP with Java, C. Thomas Wu 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 {…} ©The McGraw-Hill Companies, Inc.

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 ) ; ...}

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); } }

38 The super Reference Revisited
Intro to OOP with Java, C. Thomas Wu 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 10 ©The McGraw-Hill Companies, Inc.

39 Shadowing superclass fields vs overriding superclass methods
((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 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

40 public static void main (String[] args) {
class Firm { public static void main (String[] args) { Manager sam = new Manager ("Sam", "123 Main Line", " ", " ", ); Employee carla = new Employee ("Carla", "456 Off Line", " ", " ", ); Employee woody = new Employee ("Woody", "789 Off Rocker", " ", " ", ); woody.print(); out.println ("Paid: " + woody.pay()); System.out.println(); carla.print(); out.println ("Paid: " + carla.pay()); sam.print(); sam.awardBonus (2000); out.println ("Paid: " + sam.pay()); System.out.println(); } }

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

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; } }

43 Abstract Superclasses and Abstract Methods
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.

44 Definition: Abstract Class
Intro to OOP with Java, C. Thomas Wu 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(…). ©The McGraw-Hill Companies, Inc.

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

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

47 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

48 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

49 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

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

51 Inheritance versus Interface
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.

52 interface is a reserved word
Interfaces interface is a reserved word None of the methods in an interface are given a definition (body) public interface Doable { public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } A semicolon immediately follows each method header

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.

54 Interfaces public class CanDo implements Doable {
public void doThis () // whatever } public void doThat () // etc. implements is a reserved word Each method listed in Doable is given a definition

55 Interfaces A class can implement more than one interfaces
The interfaces are listed in the implements clause, separated by commas class 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.

56 Intro to OOP with Java, C. Thomas Wu
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 9 ©The McGraw-Hill Companies, Inc.

57 Intro to OOP with Java, C. Thomas Wu
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 10 ©The McGraw-Hill Companies, Inc.

58 Intro to OOP with Java, C. Thomas Wu
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. 11 ©The McGraw-Hill Companies, Inc.

59 public String print(); // public can be omitted
An interface Example 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

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 File class 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

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

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); }

63 An interface without including any method.
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 CloneNotSupportedExceptionexception if(obj instanceof Cloneable) copy = o.clone(); else copy = null;

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();

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

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

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 easily public 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());

68 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

69 Intro to OOP with Java, C. Thomas Wu
Overall Plan Tasks 1. Read an input text file. 2. Compute the course grades. 3. Print out the result. Input File Format ©The McGraw-Hill Companies, Inc.

70 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

71 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

72 Intro to OOP with Java, C. Thomas Wu
Step 1 Code Directory: Chapter13/Step1 Source Files: ComputeGrades.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Please use your Java IDE to view the source files and run the program. ©The McGraw-Hill Companies, Inc.

73 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

74 Intro to OOP with Java, C. Thomas Wu
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; } ©The McGraw-Hill Companies, Inc.

75 Intro to OOP with Java, C. Thomas Wu
Step 2 Code Directory: Chapter13/Step2 Source Files: ComputeGrades.java ©The McGraw-Hill Companies, Inc.

76 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

77 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

78 Intro to OOP with Java, C. Thomas Wu
Step 3 Code Directory: Chapter13/Step3 Source Files: ComputeGrades.java ©The McGraw-Hill Companies, Inc.

79 Intro to OOP with Java, C. Thomas Wu
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. ©The McGraw-Hill Companies, Inc.

80 Intro to OOP with Java, C. Thomas Wu
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; ©The McGraw-Hill Companies, Inc.

81 The buildRoster Method
Intro to OOP with Java, C. Thomas Wu 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++; } ©The McGraw-Hill Companies, Inc.

82 The createStudent Method
Intro to OOP with Java, C. Thomas Wu 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 return student; ©The McGraw-Hill Companies, Inc.

83 Intro to OOP with Java, C. Thomas Wu
Step 4 Code Directory: Chapter13/Step4 Source Files: ComputeGrades.java ©The McGraw-Hill Companies, Inc.

84 Intro to OOP with Java, C. Thomas Wu
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: ©The McGraw-Hill Companies, Inc.

85 Step 5: Finalize and Improve
Intro to OOP with Java, C. Thomas Wu 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. ©The McGraw-Hill Companies, Inc.


Download ppt "Intro to OOP with Java, C. Thomas Wu"

Similar presentations


Ads by Google