drew university1 interfaces and polymorphism 9.1 developing reusable solutions 9.2 converting...

46
Drew University 1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced Topic 9.1

Upload: priscilla-hall

Post on 18-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 1

Interfaces and Polymorphism

9.1 Developing Reusable Solutions9.2 Converting between Types

9.3 PolymorphismCommon Error 9.1Advanced Topic 9.1

Page 2: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 2

Interface

A Java interface declare a set of methods and their signatures. Unlike a class, it provides no implementation.

To realize (implement) an interface, a class must supply all the methods that the interface requires.

Page 3: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 3

public interface Comparable

Method Summary  intcompareTo(Object o)

Compares this object with the specified object for order. 

If you want your class to be Comparable, it needs a compareTo method that takes in an Object and returns an integer.

Page 4: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 4

Example

String implements Comparable We can compare two strings by invoking the String

method compareTo. String makes a promise to "define" what is means to

compare two String objects.

String s1 = <some string>;

String s2 = <some string>;

if (s2.compareTo(s1))…….

Page 5: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 5

Examples

public class Circle implements Comparable

{ public int compareTo(Object o)

// Circle must define what it means to compare two Circle objects.

}

If we want to compare two circles, we must supply the method

compareTo.

Page 6: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 6

Examples

public class Circle implements Comparable {

public int compareTo(Object o) { Circle c = (Circle) o; if (this.equals(c)) return 0; if (this.radius < c.radius) return -1; return 1;}

… // we have already defined equals for Circle. What if equals is not defined for Circle?

} this is not required here.

Page 7: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 7

Examples

public class Student implements Comparable

{ public int compareTo(Object o)

{

}

}

How do you compare students?

Page 8: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 8

Examples

public class Student implements Comparable

{ public int compareTo(Object o)

{

Student s = (Student) o;

if (equals(s)) return 0;

if (gpa < s.gpa) return -1;

return 1;

}

}

Page 9: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 9

An interface…..

"To be useful, an interface must be realized (implemented) by at least one Java class." – Rick Mercer

A class may implement MANY interfaces.

I’m a Person, I’m a Graduate,

I’m an Achiever..

Page 10: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 10

A picture (BlueJ)

<<Flier>>

fly()

SkiJumper

fly()train()

compareTo()

Bird

fly()findHome()

Airplane

fly()

Engine

<<Athlete>>train()

Page 11: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 11

Interfaces

SHOULD NOT GROW! Classes have "contracts" with an interface.

If the interface changes, all classes that realize the interface are affected!

Interfaces allow for encapsulating similar behaviors between unrelated classes.

Page 12: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 12

Interface

Contains constants, methods or both.

NO implementations.

No instance variables.

Page 13: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 13

Using interfaces

Define a set of methods as an interface. Classes that realize the interface must support

all the methods of the interface.

Create classes that implement those methods.

Compiler verifies that method calls are valid.

Page 14: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 14

Interface Example

public interface Flier

{

void fly();

}

Page 15: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 15

Interface declarations:

All methods in an interface are public. The methods in the interface are not declared as public because they are public by default.

When implementing the methods of the interface in a class, include the keyword public.

Page 16: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 16

Classes realizing Flierpublic class Bird implements Flier

{ public void fly() { System.out.println("Using my wings to fly"); }}

==================================================================public class Airplane implements Flier

{ public void fly() { System.out.println("Using my jet engines to fly"); }}

==================================================================public class SkiJumper implements Flier, Athlete, Comparable

{ public void fly() { System.out.println("Using skis to take me into the air"); }}

Page 17: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 17

Abstract

An interface is ABSTRACT. You can’t create an object of that type.

Page 18: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 18

Interfaces

Cannot be instantiated. Flier f = new Flier();NO

You can use interface name as variable type; variable can refer to an object of any class that implements the interface. Flier b = new Bird();OK Flier s = new SkiJumper();OK

Page 19: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 19

Using interfaces

Interfaces define types (sets of methods).

A variable of type Flier must refer to an object that implements methods defined by Flier, not necessarily to an instance of Flier.

Actual method invoked is defined by the object’s class, at run-time. (dynamic binding)

Page 20: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 20

polymorphism…

Dynamic Binding (overriding): Behavior can vary depending on the actual type of an object. Occurs at runtime.

Early Binding (overloading) occurs at compile time.

Page 21: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 21

polymorphism

"In the object-oriented world, polymorphism refers to the ability of different kinds of objects to respond differently to the same commands, provided that the objects belong to classes with a common ancestor."

K.N.King

Page 22: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 22

Again…

Early binding of methods occurs if the compiler selects a method from several possible candidates as with overloaded methods.

Late binding occurs if the method selection takes place when the program runs.

Page 23: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 23

The importance of IS-A

You can convert from a class type to an interface type if the class realizes the interface.

String str = "word";

Comparable p = str; // OK

You need a cast to convert from an interface type to a class type.

String str = "word";

Comparable p = str;

String t = p; // NO

Page 24: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 24

The importance of IS-A

You can convert from a class type to an interface type if the class realizes the interface.

String str = "word";

Comparable p = str; // OK

You need a cast to convert from an interface type to a class type.

String str = "word";

Comparable p = str;

String t = (String)p; // OK

Page 25: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 25

instanceof operator

The instanceof operator tests whether an object belongs to a particular type. What happens?

Flier aFlier = new SkiJumper("Joe","Smith");

Flier aFlier2 = new Airplane();

if (aFlier instanceof SkiJumper)

System.out.println("That's right.");

else

System.out.println("NOT");

Page 26: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 26

instanceof operator

The instanceof operator tests whether an object belongs to a particular type. What happens?

Flier aFlier = new SkiJumper("Joe","Smith"); Flier aFlier2 = new Airplane(); if (aFlier instanceof SkiJumper) System.out.println("That's right."); else System.out.println("NOT");

That's right.

Page 27: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 27

instanceof operator

The instanceof operator tests whether an object belongs to a particular type. What happens?

Flier aFlier = new SkiJumper("Joe","Smith"); Flier aFlier2 = new Airplane(); if (aFlier instanceof Flier) System.out.println("That's right."); else System.out.println("NOT");

Page 28: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 28

instanceof operator

The instanceof operator tests whether an object belongs to a particular type.

Flier aFlier = new SkiJumper("Joe","Smith");

Flier aFlier2 = new Airplane();

if (aFlier instanceof Flier)

System.out.println("That's right.");

else

System.out.println("NOT");

That's right.

Page 29: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 29

instanceof operator

The instanceof operator tests whether an object belongs to a particular type. What happens?

Flier aFlier = new SkiJumper("Joe","Smith"); Flier aFlier2 = new Airplane(); if (aFlier2 instanceof Flier) System.out.println("That's right."); else System.out.println("NOT");

Page 30: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 30

instanceof operator

The instanceof operator tests whether an object belongs to a particular type.

Flier aFlier = new SkiJumper("Joe","Smith");

Flier aFlier2 = new Airplane();

if (aFlier2 instanceof Flier)

System.out.println("That's right.");

else

System.out.println("NOT");

That's right.

Page 31: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 31

instanceof operator

The instanceof operator tests whether an object belongs to a particular type. What happens?

Flier aFlier = new SkiJumper("Joe","Smith"); Flier aFlier2 = new Airplane(); if (aFlier2 instanceof SkiJumper) System.out.println("That's right."); else System.out.println("NOT");

Page 32: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 32

instanceof operator

The instanceof operator tests whether an object belongs to a particular type.

Flier aFlier = new SkiJumper("Joe","Smith");

Flier aFlier2 = new Airplane();

if (aFlier2 instanceof SkiJumper)

System.out.println("That's right.");

else

System.out.println("NOT");

NOT

Page 33: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 33

Polymorphism is NOT Overloading.

Method signature refers to method name and parameters

Overloading means methods have different signatures(different parameters). Overloading usually occurs in same class. BankAccount has two constructors. One of

the constructors has one double parameter. One of the constructors has no parameters.

The compiler chooses the appropriate method.

Page 34: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 34

Polymorphism

The actual type of the object determines which method is to be called.

This is late binding (dynamic binding). The virtual machine, not the compiler, selects

the appropriate method at run time.

Page 35: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 35

Consider the following DataSet class.

//Computes the average of a set of// data values.

public class DataSet{ public DataSet() { sum = 0; count = 0; maximum = 0; }

//Adds a data value to the data // set

public void add(double x) { sum = sum + x; if (count == 0 || maximum < x)

maximum = x; count++; }

//Returns the average of the added data. public double getAverage() { if (count == 0) return 0; else return sum / count; }//Returns the largest of the added data// or 0 if no data has been addedpublic double getMaximum() { return maximum; }

private double sum; private double maximum; private int count;}

Page 36: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 36

Concerns

Suppose we wanted to find the BankAccount with the highest balance?

Suppose we wanted to find the Coin with the highest value?

Suppose we wanted to find the Student with the highest gpa?

Page 37: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 37

Solution://Computes the average of a set of// data values.

public class DataSet{ public DataSet() { sum = 0; count = 0; maximum = 0; }

//Adds a data value to the data // set public void add(BankAccount x) { sum = sum + x.getBalance(); if (count == 0 || maximum.getBalance() <

x.getBalance()) maximum = x;

count++; }

//Returns the average of the added data.public double getAverage() { if (count == 0) return 0; else return sum / count; }//Returns the largest of the added data// or 0 if no data has been addedpublic BankAccount getMaximum() { return maximum; }

private double sum; private BankAccount maximum; private int count;}

Page 38: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 38

Solution://Computes the average of a set of// data values.

public class DataSet{ public DataSet() { sum = 0; count = 0; maximum = 0; }

//Adds a data value to the data // set public void add(Coin x) { sum = sum + x.getValue(); if (count == 0 || maximum.getValue () <

x.getValue ()) maximum = x;

count++; }

//Returns the average of the added data.public double getAverage() { if (count == 0) return 0; else return sum / count; }//Returns the largest of the added data// or 0 if no data has been addedpublic Coin getMaximum() { return maximum; }

private double sum; private Coin maximum; private int count;}

Page 39: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 39

Solution://Computes the average of a set of// data values.

public class DataSet{ public DataSet() { sum = 0; count = 0; maximum = 0; }

//Adds a data value to the data // set public void add(Student x) { sum = sum + x.getGpa(); if (count == 0 || maximum.getGpa () <

x.getGpa ()) maximum = x;

count++; }

//Returns the average of the added data.public double getAverage() { if (count == 0) return 0; else return sum / count; }//Returns the largest of the added data// or 0 if no data has been addedpublic Student getMaximum() { return maximum; }

private double sum; private Student maximum; private int count;}

Page 40: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 40

Hmmmmm…

Clearly the mechanics of analyzing the data is the same in ALL cases but the details of measurement are different. BankAccount : balance Coin: value Student: gpa

Page 41: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 41

Suppose we consider the following:

public interface Measurable

{

double getMeasure();

}

Page 42: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 42

Solution://Computes the average of a set of// data values.

public class DataSet{ public DataSet() { sum = 0; count = 0; maximum = 0; }

//Adds a data value to the data // set public void add(Measurable x) { sum = sum + x.getMeasure(); if (count == 0 || maximum.getMeasure () <

x.getMeasure ()) maximum = x;

count++; }

//Returns the average of the added data.public double getAverage() { if (count == 0) return 0; else return sum / count; }//Returns the largest of the added data// or 0 if no data has been addedpublic Measurable getMaximum() { return maximum; }

private double sum; private Measurable maximum; private int count;}

Page 43: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 43

And…

public class BankAccount implements Measurable{

. . . . .

public double getMeasure()

{

return balance;

}

Page 44: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 44

Test classpublic class DataSetTest{public static void main(String[]

args) { DataSet bankData = new DataSet();

bankData.add(new BankAccount(0)); bankData.add(new

BankAccount(10000)); bankData.add(new

BankAccount(2000));

System.out.println("Average balance = " + bankData.getAverage());

Measurable max = bankData.getMaximum();

System.out.println("Highest balance = " +

max.getMeasure());

DataSet coinData = new DataSet();

coinData.add(new Coin(0.25, "quarter"));

coinData.add(new Coin(0.1, "dime"));coinData.add(new Coin(0.05,

"nickel"));

System.out.println("Average coin value = " + coinData.getAverage());

max = coinData.getMaximum();String name = ((Coin)max).getName();

System.out.println(name + " has the highest coin value of " + max.getMeasure());

}}

Page 45: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 45

And…

public class Coin implements Measurable{

. . . . .

public double getMeasure()

{

return value;

}

Page 46: Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced

Drew University 46

And…

public class Student implements Measurable{

. . . . .

public double getMeasure()

{

return gpa;

}