Chap 11
Chap 11
Chapter 11
Chapter Contents
Chapter Objectives
11.1 Introductory Example: A Trip to the
Aviary
11.2 Inheritance and Polymorphism
11.3 Example: Geological Classification
11.4 Example: An O-O Payroll Program
11.5 Graphical/Internet Java: A Function
Plotter
Chapter Objectives
Superclass
Declaring subclasses A increasingly
class B extends A general
{ . . . } "is a"
means class B is a
B increasingly
specialization of class A specialized
the "is a" relationship
Subclass
exists
a B object is an A object
Inheritance
Other names:
superclass also called "parent class"
subclass also called "child class"
These names help understand concept of
inheritance
Child class inherits characteristics of
parent class
attributes
methods
Inheritance
When we say …
class TalkingParrot extends Parrot
{ … }
then a TalkingParrot object inherits all
Parrot attributes
(which, in turn, inherits both FlyingBird
and Bird attributes)
In general, descendant classes inherit the
attributes of ancestor classes
Results of Inheritance
Consider
Bird bird1 = new Parrot("green"),
bird2 = new TalkingParrot("red",phrases);
A call to .getFood() uses the method from class Bird
Contrast invocation of .getCall()
uses methods specific to the classes Parrot and
TalkingParrot
When a method is called
system looks for local method of that name
otherwise it looks for an inherited method
Polymorphism
Principles:
A method defined in a class is inherited by all
descendants of that class
When a message is sent to an object to use method
m(), any messages that m() sends will also be sent to
the same object
If the object receiving a message does not have a
definition of the method requested, an inherited definition
is invoked
If the object receiving a message has a definition of the
requested method, that definition is invoked
Java Hierarchy
R oc k
Also:
getDescription() method in each class
returnsan
creates a actual object of this
Class instance the class object sent to
representing
class thatrockString
and reference class
to it passed to method
newInstance()
forName() method
Constructing an Object from a String
Form:
class.forName(StringVariable).newInstance()
Where:
StringVariable refers to a String containing
the name of a class
Purpose:
Returns instance of class whose name stored in
StringVariable
Created using default constructor of that class
newInstance returns that instance as an Object
It must be cast into appropriate type (usually nearest
ancestor)
11.4 Example: An O-O Payroll Program
Common attributes
salary for managers, programmers
hours and hourly wage for secretaries and
consultants
name, id, pay, etc. for all employees
Suggests superclass of Employee,
subclasses of:
Salaried employee Hourly employee
manager Consultant
programmer secretary
Hierarchy
O b jec t
S alaried H ou rly
E m p loyee E m p loyee
wages
Algorithm
Function Plotter
Function (Clear) X max 4.0 Y max 4.0
Sine
Cosine
Log10
Power Function chosen will be
graphed on the axes