Java Polymorphism: Static and Dynamic Binding, Inheritance, and Interfaces, Papers of Data Structures and Algorithms

The concept of polymorphism in java, which allows methods to change form based on the context in which they are used. It covers static and dynamic binding, polymorphism via inheritance, and polymorphism via interfaces. Examples of code demonstrating these concepts.

Typology: Papers

Pre 2010

Uploaded on 08/19/2009

koofers-user-vn0
koofers-user-vn0 🇺🇸

10 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
3/5/09
1
9.1 – Static and Dynamic Binding
! Consider the following method invocation:
pet.move();
! At some point, this invocation is bound
to the definition of the method that it invokes
! If this binding occurred statically at compile time,
then that line of code would call the same method every time
! However, Java defers method binding until run time:
this is called dynamic binding or late binding
! Late binding provides flexibility in program design
9.1 – Polymorphism == “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
! Suppose we create the following reference variable
Occupation job;
! Java allows this reference to point to an Occupation object,
or to any object of any compatible type
! This compatibility can be established
using inheritance or using interfaces
! An object reference can refer to an object of its class,
or to an object of any class related to it by inheritance
! In the example above,
it is fine for a Mammal reference to point to a Horse object
1-3
Mammal pet;
Horse barbaro = new Horse();
pet = barbaro;
Mammal
Horse
9.2 – Polymorphism via Inheritance
9.2 – Polymorphism via Inheritance
! It is the type of the object being referenced,
not the reference type,
that determines which method is invoked
! Example: Class Mammal has a method called move,
and the child Class Horse overrides it
! Now consider the following invocation
pet.move();
! Which move() is invoked?
! If pet refers to a Mammal object,
it invokes the Mammal version of move;
if pet refers to a Horse object,
it invokes the Horse version!
Mammal
Horse
+move()
+move()
! A Program that pays a set
of diverse employees
using a polymorphic
method
Why is this flexible?
9.2 – Firm.java
//********************************************************************
// Firm.java Java Foundations
//
// 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();
}
}
pf3
pf4
pf5

Partial preview of the text

Download Java Polymorphism: Static and Dynamic Binding, Inheritance, and Interfaces and more Papers Data Structures and Algorithms in PDF only on Docsity!

9.1 – Static and Dynamic Binding

Consider the following method invocation:

pet.move();

At some point, this invocation is bound

to the definition of the method that it invokes

If this binding occurred statically at compile time,

then that line of code would call the same method every time

However, Java defers method binding until run time:

this is called dynamic binding or late binding

Late binding provides flexibility in program design

9.1 – Polymorphism == “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

Suppose we create the following reference variable

Occupation job;

Java allows this reference to point to an Occupation object,

or to any object of any compatible type

This compatibility can be established

using inheritance or using interfaces

An object reference can refer to an object of its class,

or to an object of any class related to it by inheritance

In the example above,

it is fine for a Mammal reference to point to a Horse object

Mammal pet; Horse barbaro = new Horse(); pet = barbaro;

Mammal

Horse

9.2 – Polymorphism via Inheritance 9.2 – Polymorphism via Inheritance

It is the type of the object being referenced,

not the reference type,

that determines which method is invoked

Example: Class Mammal has a method called move,

and the child Class Horse overrides it

Now consider the following invocation

pet.move();

Which move() is invoked?

If pet refers to a Mammal object,

it invokes the Mammal version of move;

if pet refers to a Horse object,

it invokes the Horse version!

Mammal

Horse

+move()

+move()

A Program that pays a set

of diverse employees

using a polymorphic

method

Why is this flexible? 9.2 – Firm.java

//******************************************************************** // Firm.java Java Foundations // // 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();

9.2 – Staff.java

//******************************************************************** // Staff.java Java Foundations // //******************************************************************** Represents the personnel staff of a particular business. public class Staff { private // Constructor: StaffMember[] Sets staffList;up the list of staff members. //----------------------------------------------------------------- public Staff () { staffList = new StaffMember[5]; staffList[0] "555-0469", = new"123-45-6789", 2423.07); Executive ("Tony", "123 Main Line", staffList[1] "555-0101", = new"987-65-4321", 1246.15); Employee ("Paulie", "456 Off Line", staffList[2] "555-0000", = new"010-20-3040", 1169.23); Employee ("Vito", "789 Off Rocker", staffList[3] "555-0690", = new"958-47-3625", 10.55); Hourly ("Michael", "678 Fifth Ave.", staffList[4] "555-8374"); = new Volunteer ("Adrianna", "987 Babe Blvd.", ((Executive)staffList[0]).awardBonus (500.00); ((Hourly)staffList[3]).addHours (40); }

9.2 – Staff.java

//----------------------------------------------------------------- // Pays all staff members.

//----------------------------------------------------------------- public void payday ()

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

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

if (amount == System.out.println ("Thanks!"); 0.0) else System.out.println (”To Be Paid: " + amount); }^ } }

9.2 – StaffMember.java

abstract public { class StaffMember protected protected String name;String address; protected String phone; // //----------------------------------------------------------------- Constructor: Sets up this staff member using the specified info. public { StaffMember (String eName, String eAddress, String ePhone) name = address = eName; eAddress; }^ phone = ePhone; //----------------------------------------------------------------- // Derived classes must define the pay method for each type of employee.

//----------------------------------------------------------------- public abstract double pay();

9.2 – Volunteer.java

//******************************************************************** // Volunteer.java Java Foundations // //******************************************************************** Represents a staff member that works as a volunteer. 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; }^ }

9.2 – Employee.java

//******************************************************************** // Employee.java Java Foundations // //******************************************************************** Represents a general paid employee. public { class Employee extends StaffMember protected protected String socialSecurityNumber;double payRate; // //----------------------------------------------------------------- Constructor: Sets up this employee with the specified information. public Employee (String eName, String socSecNumber, double rate) String eAddress, String ePhone, {…} //----------------------------------------------------------------- // Returns the pay rate for this employee. //-----------------------------------------------------------------

public { double pay()

}^ return^ payRate; }

9.2 – Executive.java

//******************************************************************** // Executive.java Java Foundations // //******************************************************************** Represents an executive staff member, who can earn a bonus. public { class Executive extends Employee private double bonus; public Executive (String String eName,socSecNumber, String eAddress,double rate) String { … ePhone,} //----------------------------------------------------------------- // 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; }

9.3 – SecretTest.java

//******************************************************************** // SecretTest.java Java Foundations // // Demonstrates the use of a formal interface. //******************************************************************** public class SecretTest { //----------------------------------------------------------------- // Creates a Secret object and exercises its encryption. //----------------------------------------------------------------- public static void main (String[] args) { Secret hush = new Secret ("Wil Wheaton is my hero!"); System.out.println (hush); hush.encrypt(); System.out.println (hush); hush.decrypt(); System.out.println (hush); }^ }

9.3 – Secret.java

//----------------------------------------------------------------- // Encrypts this secret using a Caesar cipher. Has no effect if // //----------------------------------------------------------------- this secret is already encrypted.

public void encrypt { ()

if { (!encrypted) String for (int masked index=0; = ""; index < message.length(); index++) message^ masked =^ =masked;^ masked^ +^ (char)(message.charAt(index)+shift); }^ encrypted^ =^ true; } (more…)

9.3 – Secret.java

//----------------------------------------------------------------- // Decrypts and returns this secret. Has no effect if this // //----------------------------------------------------------------- secret is not currently encrypted.

public { String decrypt()

if (encrypted) { String for (int unmasked index=0; index < message.length(); = ""; index++) message =^ unmasked unmasked;^ = unmasked +^ (char)(message.charAt(index)-shift); }^ encrypted^ =^ false; }^ return^ message; //----------------------------------------------------------------- // Returns true if this secret is currently encrypted. //----------------------------------------------------------------- public boolean isEncrypted() { return encrypted; } (more…)

9.3 – Interfaces

A class can implement multiple interfaces The interfaces are listed in the implements clause The class must implement all methods in all interfaces listed in the header

class ManyThings implements interface1, interface

// all methods of both interfaces

9.3 – Java Std. Lib. Interfaces

The Java standard class library contains many helpful interfaces The Comparable interface contains one abstract method called compareTo, which is used to compare two objects The String class implements Comparable, giving us the ability to put strings in lexicographic order

9.3 – The Comparable Interface

Any class can implement Comparable to provide a mechanism for

comparing objects of that type

if (obj1.compareTo(obj2) < 0)

System.out.println ("obj1 is less than obj2");

It’s up to the programmer to determine

what makes one object < than another

I.e, you may define the compareTo method of an Employee class

to order employees by name (alphabetically)

or by employee number

The implementation of the method can be as straightforward or

as complex as needed for the situation

9.3 – The Iterator Interface

An iterator is an object that provides a means of processing

a collection of objects, one at a time

An iterator is created formally by implementing the Iterator

interface, which contains three methods

 The true if there are items left to process hasNext method returns a boolean –

 The next method returns the next object in the iteration

 The most recently returned by the remove method removes the object next method

By implementing the Iterator interface,

a class formally establishes that objects of that type are iterators

The programmer must decide how best to implement the iterator

functions

Once established, the for-each version of the for loop can be

used to process the items in the iterator

9.3 – Interfaces

You could write a class that implements certain methods (such as compareTo) without formally implementing the interface (Comparable) However, formally establishing the relationship between a class and an interface allows Java to deal with an object in certain ways Interfaces are a key aspect of OO design in Java

9.3 – 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 is referencing

current.speak();

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

9.4 – Event Processing

Polymorphism plays an important role

in the development of a Java graphical user interface

In GUIs, we establish a relationship

between a component and a listener

JButton button = new JButton();

button.addActionListener(new MyListener());

Note that the addActionListener method

is accepting a MyListener object as a parameter

In fact, we can pass the addActionListener method any object

that implements the ActionListener interface

9.4 – Event Processing

The source code for the parameter of type ActionListener addActionListener (the interface) method accepts a

Because of polymorphism, any object that implements that interface is compatible with the parameter reference variable

The component can call the actionPerformed method because

of the relationship between the listener class and the interface

Extending an adapter class to create a listener represents the same situation; the adapter class implements the appropriate

interface already