You are on page 1of 30

Saint Paul Institute

Chapter 13: Inheritance and


Polymorphism
Objectives
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 interface.
Define methods, using the protected modifier
Parse strings, using a StringTokenizer object.
Introduction
In this chapter, we will describe two important and
powerful features in object-oriented programming—
inheritance and polymorphism.
We will provide a detailed explanation and examples
of inheritance in this chapter.
The second major topic we cover in this chapter is
polymorphism, another indispensable feature in
object-oriented programming, which allows
programmers to send the same message to objects
from different classes.
13.1 Defining Classes with Inheritance
W e will actually define three classes. The first is the
Student class to incorporate behavior and data
common to both graduate and undergraduate
students. The second and third classes are the
GrauateStudent class to incorporate behavior specific
to graduate students and the UndergraduateStudent
class to incorporate behavior specific to undergraduate
students. The Students class is defined as
Student.java

GraduateStudent UndergraduateStudent
Student
+ NUM_OF_TESTS
# name
# test
# courseGrade

+ Student (): void


+ Student(String): void
+ getCourseGrade(): String
+ getName(): String
+ getTestScore (int): int
+ setName(String): void
+ setTestScore(int, int): void

UndergraduateStudent GraduateStudent

+getCourseGrade(): String +getCourseGrade(): String


13.2 Using Classes Effectively with Polymorphism
Now let’s see how the Student class and its subclasses
can be used effectively in the class roster program.
Since both undergraduate and graduate students are
enrolled in a class, should we declare the two arrays
shown bellow to maintain the class roster?
GraduateStudent gradRoster [20];
UndergraduateStudent undergradRoster [20];

student roster [40];


Elements of the roster array can be instances of either
the Student class or any of its descendant
GraduateStudent or UndergraduateStudent classes.

0 1 2 3 4 36 37 38
39
…..

:Graduate :Undergraduate :Undergraduate :Graduate


Student Student Student Student
Before showing how this array is used in the program,
we will explain the concept of polymorphism. In its
simplest form, polymorphism allows a single variable
to refer to objects from different classes. Consider, for
example, the declaration
Student student;
With this declaration, we can say not only
student = new Student ( );
but also
student = new GraduateStudent ( );
or
student = new UndergraduateStudent ( );
In other words, the single variable student is not
limited to referring to an object from the Student class
but can refer to any object from the descendant classes
of Student. In a similar manner we can say something
like
roster [0] = new GraduateStudent();
roster[1] = new UndergraduateStudent();
roster[2] = new UndergraduateStudent();
roster[3] = new GraduateStudent();
GraduateStudent grad1, grad2;
NOT grad1 = new Student();
VALID
grad2 = new UndergraduateStudent();
13.3 Inheritance and Member Accessibility
In addition to declaring members private and public, we
can declare them protected. The protected modifier is
meaningful only if used with inheritance. Consider the
following declarations:
class Super {
public int public_Super_Field;
protected int protected_Super_Field;
private int private_Super_Field;
public Super () {
public_Super_Field = 10;
protected_Super_Field = 20;
private_Super_Field = 30; }
…………..}
class Sub extends Super {
public int public_Sub_Field;
protected int protected_Sub_Field;
private int private_Sub_Field;

public Sub () {
public_Sub_Field = 100;
protected_Sub_Field = 200;
private_Sub_Field = 300;
} ………………
}
Super :Super
This shows the
inherited
Public Public
components of
Protected Protected the supperclass
Private Private are part of the
subclass instance

:Sub
:Super
Sub
Public
Public
Protected
Protected
Private
Private
Public
Protected
Class hierarchy Private Instances
You already know the difference between the public
can private modifiers. A public member is accessible to
any method, but a private member is accessible only to
the method that belong to the same class.
class Client {
public void test () {
Super mySuper = new Super ();
Sub mySub = new Sub ();
int i = mySuper.public_Super_Field;
VALID int j = mySub.public_Super_Field;
int k = mySub.public_Sub_Field; }
}
int l = mySuper.private_Super_Field;
NOT
int m = mySub.private_Sub_Field;
VALID
:Super
int n = mySub.private_Sub_Field;
Public
Protected
:Client Private

:Sub
:Super

Public
Protected
Only public members, those defined
For the class and those inherited, are Private
Visible from outside. All else is hidden
From outside. Public
Protected
Private
A protected member is accessible only to the methods
that belong to the same class or to the descendant
classes. It is inaccessible to the methods of an
unrelated class.
:Sub
The difference between public,
Private, and Protected modifiers. :Super
Public
Everything except the private
Public Protected
members of the Super class is
visible from a method of the Sub Protected Private
class. Private

Method
13.4 Inheritance and Constructors
In this section, we explain how the constructors of a
class affected by inheritance. Unlike members of a
superclass, constructors of a superclass are not
inherited by its subclasses. This means that you must
define a constructor for a class or use the default
constructor added by the compiler. As we mentioned
in Chapter 4, a default constructor is added to a class if
you do not declare any constructor for the class. A class
definition such as
class Person {
public Person ( ) {
Automatically
This statement calls the
added to the class super ( );
superclass’s constructor
by the compiler
}
public void sayHello ( ) {
System.out.println (“Well, hello”);
}
}
The statement super (); calls the superclass’s
constructor. Every class has a superclass. If the class
declaration does not explicitly designate the superclass
with the extends clause. Then the class’s superclass in
the Object class.
If you declare a constructor, then no default constructor
is added to the class. For example, if you define a class
as
class MyClass {
public MyClass ( int x ) {
…………………….. }
}
Invalid because
then a statement such as MyClass has no
MyClass test = new MyClass(); matching constructor
If the constructor you define does not contain an
explicit call to a superclass constructor, then the
compiler adds the statement super ( ) as the first
statement of the constructor. For example
class MyClass {
private int myInt ;
public MyClass ( ) {
myInt = 10; } public MyCalss ( ) {
super ( );
} myInt = 10;
}

then the compiler will rewrite the constructor to


Let’s look at another example. Consider the following
class definitions:
class Vehicle {
private String vin;
public Vehicle (String vehicleIdNumber ) {
vin = vehicleIdNumber;
}
public String getVIN ( ) {
return vin;
}
}
Since the class has a constructor, no default
constructor is added to the class. This means a
statement such as
Vehilcle myCar = new Vehilcle ( );
causes a compilation error because the class does not
have a matching constructor.
Now let’s consider a subclass definition for trucks.
class Truck extends Vehicle {
private int cargoWeightLimit;
public void setWeightLimit (int newLimit) {
cargoWeightLimit = newLimit;
}
public int getWeightLimit ( ) {
ruturn cargoWeightLimit;
}
}
if we compile this definition, we will get a compiler
error. Since no constructor is defined for the class, the
compiler adds a default constructor
public void Truck ( ) {
super ( );
}
This constructor calls the superclass’s constructor with
no arugments, bet there’s no matching constructor in
the superclass. Thus, the compilation error results.
Here’s a correct constractor have to add to Truck class:
public Truck (int weightLimit, String vin) {
super (vin);
You need to make this
cargoWeightLimit = weightLimit; call. Otherwise, the
compiler will add
} super(), which will
result in an error because
there is no matching
constructor in Vehicle
13.5 Abstract Superclass and Abstract Methods
When we define a superclass, we often do not need to
create any instances of the superclass. In Section 13.4,
we defined the Student superclass and its two
subclasses GraguateStudents and
UndergraduateStudent. Even though we can create an
instance of Student if we want to, is there a need to
create an instance of Student? If a student can be only
a graduate or a undergraduate student, then there is
no need to create an instance. we will consider two
cases. In the first case, we assume that a student must
be either a graduate or an undergraduate student. In
the second case, we assume that a student does not
have to be a graduate or an undergraduate student.
Case 1: Student Must Be Undergraduate or
Graduate
For the case where a student must be a graduate or an
undergraduate student, we only need instances of
GraduateStudent and UndergraduateStudent. So we
must define the Student class in such a way that no
instances of it can be created. One way is to define
Student as an abstract class. An abstract class is a
class defined with the modifier abstract, and no
instances can be created from an abstract class. Let’s
see how the abstract Student class is defined.
abstract class Student {
protected final static int NUM_OF_TESTS = 3;
protected String name; Abstract class here
protected int[ ] test; can not create
instances access!
protected String courseGrade;
public Student ( ) { Abstract method has
no method body, just a
this (“No name”); }
semicolon
public Student (String studentName) {
name = studentName;
test = new int (NUM_OF_TESTS];
courseGrade = “*****”; }
abstract public void computeCourseGrade ( );
//same as methods as before…….}
An abstract method is a method with the keyword
abstract, and it ends with a semicolon instead of a
method body. A class is abstract if the class contains
an abstract method or does not provide an
implementation of an inherited abstract method. We
say a method is implemented if it has a method body.
Case 2: Student Does Not Have to Be
Undergraduate or Graduate
For the second case, where a students does not have to
be a graduate or an undergraduate student, we can
design classes in two different ways. The first approach
is to make the Student class instantiable. The second
approach is to leave the Student class abstract and add
a third subclass, say, OtherStudent, to handle a
student who is neither a graduate nor undergraduate
students nonregular student.
13.6 Inheritance versus Interface
Java interface and inheritance are language features
used to support object-oriented modeling. They are
similar because they are both used to model an IS-A
relationship. Consider, for example, the following class
definitions:
class AddressBookVer1 implements AddressBook {
……………………………………………………………………………}
class SavingsAccount extends Account {
………………………………………………………….}
We use the Java interface to share common behavior
(defined by its abstract methods) among the instances
of unrelated classes. And one class can implement
multiple interfaces. For example, we can define a single
Person class that implements multiple interfaces such
Driver, Commuter, and Biker.
We use inheritance, on the other hand, to share
common code (including both data members and
methods) among the instances of related classes. And
a single subclass can extend at most one superclass.
For example GraduateStudent and
UndergraduateStudent classes are subclass of the
Student class.

You might also like