Lecture 4.Part1
Lecture 4.Part1
Inheritance
Objectives
• After you have read and studied, you should be able to
• 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.
• Differentiate the abstract classes and Java interfaces.
• Define methods, using the protected modifier.
• Parse strings, using a String Tokenizer object.
Polymorphism
• Polymorphism is another indispensable feature in object-
oriented programming,
• which allows programmers to send the same message to objects
from different classes.
• Depending on the receiver object, different methods are
executed.
• Polymorphism helps us write code that is easy to modify and
extend
Simple Example
• We can effectively model Pet
class Pet {
private String name;
public String getName() {
return name;
}
public void setName(String petName) {
name = petName;
}
public String speak( ) {
return “I’m your cuddly little pet.”;
}
}
Subclasses of The Pet Class
class Cat extends Pet {
public String speak( ) { The Cat subclass
return “Don’t give me orders.\n” + overrides the
“I speak only when I want to.”; inherited method
speak.
}
}
System.out.println( ((Dog)p).fetch( ) );
Defining Classes with Inheritance
• Case Study:
• Suppose we want 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.
Modeling Two Types of Students
• There are two ways to design the classes to model
undergraduate and graduate students.
• We can define two unrelated classes, one for undergraduates and
one for graduates.
• We can model the two kinds of students by using classes that are
related in an inheritance hierarchy.
• Two classes are unrelated if they are not connected in
an inheritance relationship.
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.
Inheritance Hierarchy
The Protected Modifier
• The modifier protected makes a data member or method visible and
accessible to the instances of the class and the descendant classes.
Pet myPet;
Chapter 13 - 18
Sample Polymorphic Message
• To compute the course grade using the roster array, we execute
int undergradCount = 0;
for (int i = 0; i < numberOfStudents; i++) {
if ( roster[i] instanceof UndergraduateStudent ) {
undergradCount++;
}
}
Inheritance and Member Accessibility
• We use the following visual representation of
inheritance to illustrate data member accessibility.
Instances
Class Hierarchy
The Effect of Three Visibility Modifiers
package one
package two
Accessibility of Super from Sub
• Everything except the private members of the Super class is
visible from a method of the Sub class.
Accessibility from Another Instance
• Data members accessible from an instance are also accessible
from other instances of the same class.
Inheritance and Constructors
• Unlike members of a superclass, constructors of a superclass
are not inherited by its subclasses.
• You must define a constructor for a class or use the default
constructor added by the compiler.
• The statement
super();
calls the superclass’s constructor.
• If the class declaration does not explicitly designate the
superclass with the extends clause, then the class’s superclass
is the Object class.
…
…
Abstract Superclasses and Abstract Methods
• 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.
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.
Which Approach to Use
Chapter 13 - 35
Development Steps
• We will develop this program in five steps:
Chapter 13 - 36
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.
Chapter 13 - 37
Step 1 Code
Program source file is too big to list here. From now on, we ask
you to view the source files using your Java IDE.
Directory: Chapter13/Step1
Chapter 13 - 38
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.
Chapter 13 - 39
Step 2 Design
• We design and implement the printResult method
• We use the helper class OutputBox for displaying
the result.
Chapter 13 - 40
Step 2 Code
Directory: Chapter13/Step2
Chapter 13 - 41
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.
Chapter 13 - 42
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.
Chapter 13 - 43
Step 3 Code
Directory: Chapter13/Step3
Chapter 13 - 44
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.
Chapter 13 - 45
Step 4 Design
• We design and implement the core functionality of
the program—the readData method
• We can express its logic as
Chapter 13 - 46
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++;
}
}
}
Chapter 13 - 47
The createStudent Method
• We use the StringTokenizer class to break down items in a single
line of input
Chapter 13 - 48
Step 4 Code
Directory: Chapter13/Step4
Chapter 13 - 49
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:
Chapter 13 - 50
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.