Vous êtes sur la page 1sur 60

Inheritance and Polymorphism

Polymorphism
 The term polymorphism literally means "having
many forms"

 A polymorphic reference is a variable that can refer


to different types of objects at different points in time

 The method invoked through a polymorphic


reference can change from one invocation to the next

 All object references in Java are potentially


polymorphic
Java Programming: Program Design Including Data Structures 2
References and Inheritance
 An object reference can refer to an object of its class,
or to an object of any class related to it by inheritance
 For example, if the Christmas class is derived
from a class called Holiday, then a Holiday
reference could be used to point to a Christmas
object
Holiday
Holiday day;
day = new Christmas();
Christmas

© 2004 Pearson Addison-Wesley. All rights reserved 9-3


References and Inheritance
 Assigning a child object to a parent reference is
considered to be a widening conversion, and can be
performed by simple assignment

 Assigning an parent object to a child reference can be


done also, but it is considered a narrowing
conversion and must be done with a cast

 The widening conversion is the most useful

© 2004 Pearson Addison-Wesley. All rights reserved 9-4


Polymorphism via Inheritance
 It is the type of the object being referenced, not the
reference type, that determines which method is
invoked
 Suppose the Holiday class has a method called
celebrate, and the Christmas class overrides it

 Now consider the following invocation:


day.celebrate();

 If day refers to a Holiday object, it invokes the


Holiday version of celebrate; if it refers to a
Christmas object, it invokes the Christmas
© 2004 Pearson Addison-Wesley. All rights reserved 9-5
version
Polymorphism via Inheritance
 Consider the following class hierarchy:
StaffMember

Volunteer Employee

Executive Hourly

© 2004 Pearson Addison-Wesley. All rights reserved 9-6


Firm.java
//*************************************************************
// Firm.java Author: Lewis/Loftus
//
// Demonstrates polymorphism via inheritance.
//*************************************************************

public class Firm


{
//----------------------------------------------------------
// Creates a staff of employees for a firm and pays them.
//----------------------------------------------------------
public static void main (String[] args)
{
Staff personnel = new Staff();

personnel.payday();
}
}
© 2004 Pearson Addison-Wesley. All rights reserved 9-7
Staff.java
public class Staff
{
private StaffMember[] staffList;

//----------------------------------------------------------
// Constructor: Sets up the list of staff members.
//----------------------------------------------------------
public Staff ()
{
staffList = new StaffMember[6];

staffList[0] = new Executive ("Sam", "123 Main Line",


"555-0469", "123-45-6789", 2423.07);

staffList[1] = new Employee ("Carla", "456 Off Line",


"555-0101", "987-65-4321", 1246.15);
staffList[2] = new Employee ("Woody", "789 Off Rocker",
"555-0000", "010-20-3040", 1169.23);
© 2004 Pearson Addison-Wesley. All rights reserved 9-8
staffList[3] = new Hourly ("Diane", "678 Fifth Ave.",
Staff.java
staffList[4] = new Volunteer ("Norm", "987 Suds Blvd.",
"555-8374");
staffList[5] = new Volunteer ("Cliff", "321 Duds Lane",
"555-7282");

((Executive)staffList[0]).awardBonus (500.00);

((Hourly)staffList[3]).addHours (40);
}

© 2004 Pearson Addison-Wesley. All rights reserved 9-9


Staff.java
//----------------------------------------------------------
// Pays all staff members.
//----------------------------------------------------------
public void payday ()
{
double amount;

for (int count=0; count < staffList.length; count++)


{
System.out.println (staffList[count]); // polymorphic

amount = staffList[count].pay(); // polymorphic

if (amount == 0.0)
System.out.println ("Thanks!");
else
System.out.println ("Paid: " + amount);

System.out.println ("------------------------------");
© 2004 Pearson Addison-Wesley. All rights reserved 9-10
}
StaffMember.java
abstract public class StaffMember
{
protected String name;
protected String address;
protected String phone;

//----------------------------------------------------------
// Constructor: Sets up this staff member using the
// specified information.
//----------------------------------------------------------
public StaffMember (String eName, String eAddress,
String ePhone)
{
name = eName;
address = eAddress;
phone = ePhone;
}

© 2004 Pearson Addison-Wesley. All rights reserved 9-11


StaffMember.java
//----------------------------------------------------------
// Returns a string including the basic employee
// information.
//----------------------------------------------------------
public String toString()
{
String result = "Name: " + name + "\n";

result += "Address: " + address + "\n";


result += "Phone: " + phone;

return result;
}

//----------------------------------------------------------
// Derived classes must define the pay method for each type
// of employee.
//----------------------------------------------------------
public abstract double pay();
© 2004 Pearson Addison-Wesley. All rights reserved 9-12
}
Volunteer.java
public class Volunteer extends StaffMember
{
//----------------------------------------------------------
// Constructor: Sets up this volunteer using the specified
// information.
//----------------------------------------------------------
public Volunteer (String eName, String eAddress,
String ePhone)
{
super (eName, eAddress, ePhone);
}

//----------------------------------------------------------
// Returns a zero pay value for this volunteer.
//----------------------------------------------------------
public double pay()
{
return 0.0;
}
© 2004 Pearson Addison-Wesley. All rights reserved 9-13
}
Employee.java
public class Employee extends StaffMember
{
protected String socialSecurityNumber;
protected double payRate;

//----------------------------------------------------------
// Constructor: Sets up this employee with the specified
// information.
//----------------------------------------------------------
public Employee (String eName, String eAddress,
String ePhone, String socSecNumber,
double rate)
{
super (eName, eAddress, ePhone);

socialSecurityNumber = socSecNumber;
payRate = rate;
}
© 2004 Pearson Addison-Wesley. All rights reserved 9-14
Employee.java
//----------------------------------------------------------
// Returns information about an employee as a string.
//----------------------------------------------------------
public String toString()
{
String result = super.toString();

result += "\nSocial Security Number: " +


socialSecurityNumber;

return result;
}

//----------------------------------------------------------
// Returns the pay rate for this employee.
//----------------------------------------------------------
public double pay()
{
return payRate;
© 2004 Pearson Addison-Wesley. All rights reserved 9-15
}
Executive.java
public class Executive extends Employee
{
private double bonus;

//----------------------------------------------------------
// Constructor: Sets up this executive with the specified
// information.
//----------------------------------------------------------
public Executive (String eName, String eAddress,
String ePhone, String socSecNumber,
double rate)
{
super (eName, eAddress, ePhone, socSecNumber, rate);

bonus = 0; // bonus has yet to be awarded


}

© 2004 Pearson Addison-Wesley. All rights reserved 9-16


Executive.java
//----------------------------------------------------------
// Awards the specified bonus to this executive.
//----------------------------------------------------------
public void awardBonus (double execBonus)
{
bonus = execBonus;
}

//----------------------------------------------------------
// Computes and returns the pay for an executive, which is
// the regular employee payment plus a one-time bonus.
//----------------------------------------------------------
public double pay()
{
double payment = super.pay() + bonus;

bonus = 0;

return payment;
© 2004 Pearson Addison-Wesley. All rights reserved 9-17
}
Hourly.java
public class Hourly extends Employee
{
private int hoursWorked;

//----------------------------------------------------------
// Constructor: Sets up this hourly employee using the
// specified information.
//----------------------------------------------------------
public Hourly (String eName, String eAddress, String ePhone,
String socSecNumber, double rate)
{
super (eName, eAddress, ePhone, socSecNumber, rate);

hoursWorked = 0;
}

© 2004 Pearson Addison-Wesley. All rights reserved 9-18


Hourly.java
//----------------------------------------------------------
// Adds the specified number of hours to this employee's
// accumulated hours.
//----------------------------------------------------------
public void addHours (int moreHours)
{
hoursWorked += moreHours;
}

//----------------------------------------------------------
// Computes and returns the pay for this hourly employee.
//----------------------------------------------------------
public double pay()
{
double payment = payRate * hoursWorked;

hoursWorked = 0;

return payment;
© 2004 Pearson Addison-Wesley. All rights reserved 9-19
}
Hourly.java
//----------------------------------------------------------
// Returns information about this hourly employee as a
// string.
//----------------------------------------------------------
public String toString()
{
String result = super.toString();

result += "\nCurrent hours: " + hoursWorked;

return result;
}
}

© 2004 Pearson Addison-Wesley. All rights reserved 9-20


Name: Sam
Address: 123 Main Line
Output Name: Diane
Address: 678 Fifth Ave.
Phone: 555-0469 Phone: 555-0690
Social Security Number: 123-45-6789 Social Security Number: 958-47-3625
Paid: 2923.07 Current hours: 40
----------------------------------- Paid: 422.0
Name: Carla -----------------------------------
Address: 456 Off Line Name: Norm
Phone: 555-0101 Address: 987 Suds Blvd.
Social Security Number: 987-65-4321 Phone: 555-8374
Paid: 1246.15 Thanks!
----------------------------------- -----------------------------------
Name: Woody Name: Cliff
Address: 789 Off Rocker Address: 321 Duds Lane
Phone: 555-0000 Phone: 555-7282
Social Security Number: 010-20-3040 Thanks!
Paid: 1169.23 -----------------------------------
-----------------------------------

© 2004 Pearson Addison-Wesley. All rights reserved 9-21


Outline
Polymorphic References
Polymorphism via Inheritance
Polymorphism via Interfaces
Sorting
Searching
Event Processing Revisited
File Choosers and Color Choosers
Sliders

© 2004 Pearson Addison-Wesley. All rights reserved 9-22


Polymorphism via Interfaces
 An interface name can be used as the type of an
object reference variable
Speaker current;

 The current reference can be used to point to any


object of any class that implements the Speaker
interface
 The version of speak that the following line
invokes depends on the type of object that current
isPearson
© 2004 referencing
Addison-Wesley. All rights reserved 9-23
Polymorphism via Interfaces
 Suppose two classes, Philosopher and Dog, both
implement the Speaker interface, providing
distinct versions of the speak method

 In the following code, the first call to speak


invokes one version and the second invokes another:
Speaker guest = new Philospher();
guest.speak();
guest = new Dog();
guest.speak();

© 2004 Pearson Addison-Wesley. All rights reserved 9-24


Review: Classes
 User-defined data types
 Defined using the “class” keyword
 Each class has associated
 Data members (any object type)
 Methods that operate on the data
 New instances of the class are declared using the
“new” keyword
 “Static” members/methods have only one copy,
regardless of how many instances are created
Java Programming: Program Design Including Data Structures 25
Example: Shared Functionality
public class Student { public class Professor {
String name; String name;
char gender; char gender;
Date birthday; Date birthday;
Vector<Grade> grades; Vector<Paper> papers;

double getGPA() { int getCiteCount() {


… …
} }

int getAge(Date today) { int getAge(Date today) {


… …
} }
} }

Java Programming: Program Design Including Data Structures 26


public class Person {
String name;
char gender;
Date birthday;

int getAge(Date today) {



}
}

public class Student public class Professor


extends Person { extends Person {

Vector<Grade> grades; Vector<Paper> papers;

double getGPA() { int getCiteCount() {


… …
} }
} }
Java Programming: Program Design Including Data Structures 27
Inheritance
 “is-a” relationship
 Single inheritance:
 Subclass is derived from one existing class
(superclass)
 Multiple inheritance:
 Subclass is derived from more than one superclass
 Not supported by Java
 A class can only extend the definition of one class

Java Programming: Program Design Including Data Structures 28


Inheritance (continued)

modifier(s) class ClassName extends ExistingClassName


modifier(s)
{
memberList
}

Java Programming: Program Design Including Data Structures 29


Inheritance:
class Circle Derived from
class Shape
public class Circle extends Shape
{
.
.
.
}

Java Programming: Program Design Including Data Structures 30


Inheritance
 Allow us to specify relationships between types
 Abstraction, generalization, specification
 The “is-a” relationship
 Examples?

 Why is this useful in programming?


 Allows for code reuse
 More intuitive/expressive code
Code Reuse
 General functionality can be written once and applied
to *any* subclass
 Subclasses can specialize by adding members and
methods, or overriding functions
Inheritance: Adding Functionality
 Subclasses have all of the data members and
methods of the superclass
 Subclasses can add to the superclass
 Additional data members
 Additional methods
 Subclasses are more specific and have more
functionality
 Superclasses capture generic functionality common
across many types of objects

Java Programming: Program Design Including Data Structures 33


public class Person {
String name;
char gender;
Date birthday;

int getAge(Date today) {



}
}

public class Student public class Professor


extends Person { extends Person {

Vector<Grade> grades; Vector<Paper> papers;

double getGPA() { int getCiteCount() {


… …
} }
} }
Java Programming: Program Design Including Data Structures 34
Brainstorming
 What are some other examples of possible
inheritance hierarchies?
 Person -> student, faculty…
 Shape -> circle, triangle, rectangle…
 Other examples???

Java Programming: Program Design Including Data Structures 35


UML Diagram: Rectangle

What if we want to implement a 3d box object?

Java Programming: Program Design Including Data Structures 36


Objects myRectangle and
myBox
Rectangle myRectangle = new Rectangle(5, 3);
Box myBox = new Box(6, 5, 4);

Java Programming: Program Design Including Data Structures 37


UML Class Diagram: class Box

Both a Rectangle and a Box have a surface area,


but they are computed differently
Java Programming: Program Design Including Data Structures 38
Overriding Methods
 A subclass can override (redefine) the methods of the
superclass
 Objects of the subclass type will use the new method
 Objects of the superclass type will use the original

Java Programming: Program Design Including Data Structures 39


class Rectangle
public double area()
{
return getLength() * getWidth();
}

class Box
public double area()
{
return 2 * (getLength() * getWidth()
+ getLength() * height
+ getWidth() * height);
}

Java Programming: Program Design Including Data Structures 40


final Methods
 Can declare a method of a class final using the
keyword final

public final void doSomeThing()


{
//...
}

 If a method of a class is declared final, it cannot


be overridden with a new definition in a derived class

Java Programming: Program Design Including Data Structures 41


Calling methods of the superclass
 To write a method’s definition of a subclass, specify a
call to the public method of the superclass
 If subclass overrides public method of superclass,
specify call to public method of superclass:
super.MethodName(parameter list)
 If subclass does not override public method of
superclass, specify call to public method of superclass:
MethodName(parameter list)

Java Programming: Program Design Including Data Structures 42


class Box

public void setDimension(double l, double w, double h)


{
super.setDimension(l, w);
if (h >= 0)
height = h;
else
height = 0;
}}

Box overloads the method setDimension


(Different parameters)

Java Programming: Program Design Including Data Structures 43


Defining Constructors of the
Subclass
 Call to constructor of superclass:
 Must be first statement
 Specified by super parameter list

public Box()
{
super();
height = 0;
}

public Box(double l, double w, double h)


{
super(l, w);
height = h;
}
Java Programming: Program Design Including Data Structures 44
Access Control
 Access control keywords define which classes can
access classes, methods, and members

Modifier Class Package Subclass World


public Y Y Y Y
protected Y Y Y N
none Y Y N N
private Y N N N

Java Programming: Program Design Including Data Structures 45


Polymorphism
 Can treat an object of a subclass as an object of its
superclass
 A reference variable of a superclass type can point to
an object of its subclass
Person name, nameRef;
PartTimeEmployee employee, employeeRef;
name = new Person("John", "Blair");
employee = new PartTimeEmployee("Susan", "Johnson",
12.50, 45);
nameRef = employee;
System.out.println("nameRef: " + nameRef);

nameRef: Susan Johnson wages are: $562.5

Java Programming: Program Design Including Data Structures 46


Polymorphism
 Late binding or dynamic binding (run-time binding):
 Method to be executed is determined at execution
time, not compile time
 Polymorphism: to assign multiple meanings to the
same method name
 Implemented using late binding

Java Programming: Program Design Including Data Structures 47


Polymorphism (continued)
 The reference variable name or nameRef can point
to any object of the class Person or the class
PartTimeEmployee
 These reference variables have many forms, that is,
they are polymorphic reference variables
 They can refer to objects of their own class or to
objects of the classes inherited from their class

Java Programming: Program Design Including Data Structures 48


Polymorphism and References

Shape myShape = new Circle(); // allowed


Shape myShape2 = new Rectangle(); // allowed
Rectangle myRectangle = new Shame(); // NOT allowed

Java Programming: Program Design Including Data Structures 49


Polymorphism (continued)
 Can also declare a class final using the keyword
final
 If a class is declared final, then no other class
can be derived from this class
 Java does not use late binding for methods that are
private, marked final, or static
 Why not?

Java Programming: Program Design Including Data Structures 50


Casting
 You cannot automatically make reference variable of
subclass type point to object of its superclass
 Suppose that supRef is a reference variable of a
superclass type and supRef points to an object of its
subclass:
 Can use a cast operator on supRef and make a
reference variable of the subclass point to the object
 If supRef does not point to a subclass object and you
use a cast operator on supRef to make a reference
variable of the subclass point to the object, then Java
will throw a ClassCastException—indicating
that the class cast is not allowed

Java Programming: Program Design Including Data Structures 51


Polymorphism (continued)
 Operator instanceof: determines whether a
reference variable that points to an object is of a
particular class type
 This expression evaluates to true if p points to an
object of the class BoxShape; otherwise it
evaluates to false:
p instanceof BoxShape

Java Programming: Program Design Including Data Structures 52


Abstract Methods
 A method that has only the heading with no body
 Must be implemented in a subclass
 Must be declared abstract
public double abstract area();
public void abstract print();
public abstract object larger(object,
object);
void abstract insert(int insertItem);

Java Programming: Program Design Including Data Structures 53


Abstract Classes
 A class that is declared with the reserved word
abstract in its heading
 An abstract class can contain instance variables,
constructors, finalizers, and non-abstract methods
 An abstract class can contain abstract methods

Java Programming: Program Design Including Data Structures 54


Abstract Classes (continued)
 If a class contains an abstract method, the class must
be declared abstract
 You cannot instantiate an object of an abstract class
type; can only declare a reference variable of an
abstract class type
 You can instantiate an object of a subclass of an
abstract class, but only if the subclass gives the
definitions of all the abstract methods of the
superclass

Java Programming: Program Design Including Data Structures 55


Abstract Class Example
public abstract class AbstractClassExample
{
protected int x;
public void abstract print();

public void setX(int a)


{
x = a;
}

public AbstractClassExample()
{
x = 0;
}
}

Java Programming: Program Design Including Data Structures 56


Interfaces
 A class that contains only abstract methods and/or
named constants
 How Java implements multiple inheritance
 To be able to handle a variety of events, Java allows
a class to implement more than one interface

Java Programming: Program Design Including Data Structures 57


Composition
 Another way to relate two classes
 One or more members of a class are objects of
another class type
 “has-a” relation between classes
 For example, “every person has a date of birth”

Java Programming: Program Design Including Data Structures 58


Composition Example

Java Programming: Program Design Including Data Structures 59


Composition Example
(continued)

Java Programming: Program Design Including Data Structures 60

Vous aimerez peut-être aussi