33
Chapter 11 – Chapter 11 – Interfaces and Interfaces and Polymorphism Polymorphism

Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

Embed Size (px)

Citation preview

Page 1: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

Chapter 11 – Chapter 11 – Interfaces and Interfaces and PolymorphismPolymorphism

Page 2: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

Chapter GoalsChapter Goals

Learn about interfacesLearn about interfaces

Convert between class and interface Convert between class and interface referencesreferences

Understand the concept of Understand the concept of polymorphismpolymorphism

Understand the purpose of interfaces Understand the purpose of interfaces to decouple classesto decouple classes

Page 3: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

Interfaces and Interfaces and PolymorphismPolymorphism

Interfaces are important for Interfaces are important for developing reusable software developing reusable software componentscomponents

Polymorphism is the principal at the Polymorphism is the principal at the heart of this process – a key heart of this process – a key component of object oriented component of object oriented programmingprogramming

Page 4: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

Concept #1: InterfacesConcept #1: Interfaces

If you think of a class as a sphere – If you think of a class as a sphere – the interface is the surfacethe interface is the surface How will code behave (what methods How will code behave (what methods

will it define)will it define) Ex. Javadocs are an Ex. Javadocs are an interfaceinterface to the to the

underlying class – defines how the class underlying class – defines how the class behavesbehaves

Page 5: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

InterfacesInterfaces

Java uses interfaces to define a common Java uses interfaces to define a common set of behaviors that varying objects can set of behaviors that varying objects can shareshare Define an interface that only specifies Define an interface that only specifies

methods that must be used (not how to use methods that must be used (not how to use them)them)

Create a class that Create a class that implementsimplements this interface this interface – it is signing a contract that it will define all – it is signing a contract that it will define all of the methods the interface specifiesof the methods the interface specifies

This contract insures that we can make This contract insures that we can make assumptions about what methods are assumptions about what methods are available (without looking at a Javadoc)available (without looking at a Javadoc)

Page 6: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

InterfacesInterfaces

An interface is much like a class in An interface is much like a class in terms of how it is defined exceptterms of how it is defined except Not instantiableNot instantiable No fields (except constants)No fields (except constants) No body to the methods, only No body to the methods, only

signaturessignatures Methods are automatically Methods are automatically publicpublic

Page 7: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

ExampleExample

public public interfaceinterface KeyListener { KeyListener {

public void keyHit(char c); public void keyHit(char c);

}} Anything that implements this Anything that implements this

interface must define a method interface must define a method keyHit( ) to handle keyboard entrykeyHit( ) to handle keyboard entry

Interfaces only define the minimum Interfaces only define the minimum methods, you can have as many methods, you can have as many others as you wantothers as you want

Page 8: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

Static constant fieldsStatic constant fields

Interfaces can have class constant Interfaces can have class constant fieldsfields Omit Omit public static finalpublic static final – automatically – automatically

makes fields this waymakes fields this way

public interface SwingConstantspublic interface SwingConstants

{{

int NORTH = 1;int NORTH = 1;

int NORTHEAST = 2;int NORTHEAST = 2;

int EAST = 3;int EAST = 3;

……

}}

Page 9: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

11.1 Using Interfaces for 11.1 Using Interfaces for Code ReuseCode Reuse

Use Use interface typesinterface types to make code to make code more generalmore general Identify common/essential operationsIdentify common/essential operations

Let’s say there is a class DataSet Let’s say there is a class DataSet that keeps track of a running total of that keeps track of a running total of real numbersreal numbers

Page 10: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

public class DataSet{public class DataSet{private double sum, maximum; private double sum, maximum; private int count;private int count;

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

maximum = x; maximum = x; count++; count++;

} } public double getMaximum(){ public double getMaximum(){

return maximum;return maximum;}}public int getCount(){public int getCount(){

return count;return count;}}

}}

Page 11: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

Problem: Only works for numbersProblem: Only works for numbers What if we wanted to keep track of What if we wanted to keep track of

BankAccounts?BankAccounts?

Page 12: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

public class DataSet{public class DataSet{private double sum;private double sum;private BankAccount maximum;private BankAccount maximum;private int count; private int count;

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

maximum = x;maximum = x;count++;count++;

}}public BankAccount getMaximum(){public BankAccount getMaximum(){

return maximum;return maximum;}}public int getCount(){public int getCount(){

return count;return count;}}

} }

Page 13: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

What if we want to do the same for What if we want to do the same for Coins?Coins?

Page 14: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

public class DataSet{public class DataSet{private double sum;private double sum;private Coin maximum;private Coin maximum;private int count; private int count;

public void add(Coin x) { public void add(Coin x) { sum = sum + x.getValue(); sum = sum + x.getValue(); if (count == 0if (count == 0 || maximum.Value() < x.getValue())|| maximum.Value() < x.getValue())

maximum = x;maximum = x;count++;count++;

}}public Coin getMaximum(){public Coin getMaximum(){

return maximum;return maximum;}}public int getCount(){public int getCount(){

return count;return count;}}

}}

Page 15: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

The mechanics of analyzing the data is The mechanics of analyzing the data is the same in all cases; details of the same in all cases; details of measurement differ measurement differ We have three classes doing three very We have three classes doing three very

similar tasks, but they all contain similar tasks, but they all contain redundant coderedundant code

Classes could agree on a method Classes could agree on a method getMeasure( ) that obtains the measure getMeasure( ) that obtains the measure to be used in the analysis to be used in the analysis

Page 16: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

We can then implement a single We can then implement a single reusable reusable DataSet DataSet class whose add class whose add method looks like this: method looks like this:

sum = sum + x.getMeasure(); sum = sum + x.getMeasure();

if (count == 0 if (count == 0 || maximum.getMeasure() < x.getMeasure()) || maximum.getMeasure() < x.getMeasure())

{{maximum = x; count++; maximum = x; count++;

}}

Page 17: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

InterfacesInterfaces

What type is x? What type is x? We want x to be an type of object that We want x to be an type of object that

has a getMeasure( ) methodhas a getMeasure( ) method

Interfaces allow us to ensure that Interfaces allow us to ensure that this is the casethis is the case

Page 18: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

An An interface typeinterface type is used to specify is used to specify required operations for a classrequired operations for a class

public interface Measurable public interface Measurable

{{

double getMeasure(); double getMeasure();

} }

Page 19: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

public class DataSet{public class DataSet{private double sum;private double sum;private private MeasurableMeasurable maximum; maximum;private int count; private int count;

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

maximum = x;maximum = x;count++;count++;

}}public public MeasurableMeasurable getMaximum(){ getMaximum(){

return maximum;return maximum;}}public int getCount(){public int getCount(){

return count;return count;}}

} }

Page 20: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

InterfacesInterfaces

Now Now DataSetDataSet can be used for any class can be used for any class that implements the that implements the MeasurableMeasurable interfaceinterface

To implement an interface, use To implement an interface, use implementsimplements reserved word and reserved word and implement all methods specified in implement all methods specified in the interfacethe interface

Page 21: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

Defining interfacesDefining interfaces

public interface public interface InterfaceNameInterfaceName

{{

// // method signaturesmethod signatures

}}

Page 22: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

ImplementsImplements

public class public class ClassNameClassName implements Measurable implements Measurable

{{

public double getMeasure() public double getMeasure()

{{

ImplementationImplementation

}}

// Additional methods and fields// Additional methods and fields

}} Note that interface names often end in –ableNote that interface names often end in –able

Describe an “ability” of the classDescribe an “ability” of the class Comparable, Readable, Appendable, Comparable, Readable, Appendable,

Page 23: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

Implementing interfacesImplementing interfaces

public class public class ClassNameClassName implements implements InterfaceName, InterfaceName, ...InterfaceName, InterfaceName, ...

{ {

// methods // methods

// instance variables// instance variables

}}

Can implement multiple interfacesCan implement multiple interfaces

Page 24: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

public class BankAccount implements Measurablepublic class BankAccount implements Measurable

{{

public double getMeasure() public double getMeasure()

{{

return balance;return balance;

}}

// Additional methods and fields// Additional methods and fields

}}

Page 25: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

11.2 Converting between 11.2 Converting between classes and interfacesclasses and interfaces

You can convert from a class type to You can convert from a class type to an interface type, provided the class an interface type, provided the class implements the interface implements the interface

BankAccount account = new BankAccount(10000);BankAccount account = new BankAccount(10000);

Measurable x = account; // OK Measurable x = account; // OK

Coin dime = new Coin(0.1, "dime");Coin dime = new Coin(0.1, "dime");

Measurable x = dime; // Also OKMeasurable x = dime; // Also OK

Page 26: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

Cannot convert between unrelated Cannot convert between unrelated typestypesMeasurable x = new Rectangle(5, 10, 20, Measurable x = new Rectangle(5, 10, 20, 30); // ERROR30); // ERROR

Because Because RectangleRectangle doesn't implement doesn't implement MeasurableMeasurable

Page 27: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

We know that since Coin implements We know that since Coin implements Measurable, we can assign a Coin Measurable, we can assign a Coin object to a Measurable reference object to a Measurable reference variablevariable

But what about the other way? But what about the other way? Could we always assign a Could we always assign a Measurable object to a Coin Measurable object to a Coin reference variable?reference variable?

Page 28: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

Type castingType casting

Add coin objects to Add coin objects to DataSetDataSetDataSet coinData = new DataSet();DataSet coinData = new DataSet();coinData.add(new Coin(0.25, "quarter"));coinData.add(new Coin(0.25, "quarter"));coinData.add(new Coin(0.1, "dime"));coinData.add(new Coin(0.1, "dime"));. . .. . .Measurable max = coinData.getMaximum(); Measurable max = coinData.getMaximum();

What can you do with it? It's not of What can you do with it? It's not of type Cointype CoinString name = max.getName(); // ERRORString name = max.getName(); // ERROR

Page 29: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

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

You know it's a coin, but the You know it's a coin, but the compiler doesn't. Apply a cast:compiler doesn't. Apply a cast:

Coin maxCoin = (Coin) max;Coin maxCoin = (Coin) max;String name = maxCoin.getName(); String name = maxCoin.getName();

Page 30: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

If you are wrong and max isn't a If you are wrong and max isn't a coin, the compiler throws an coin, the compiler throws an exception exception

Compare to casting numbers:Compare to casting numbers: When casting number types you agree When casting number types you agree

to the information lossto the information loss When casting object types you agree to When casting object types you agree to

the risk of causing an exception the risk of causing an exception

Page 31: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

11.3 Polymorphism11.3 Polymorphism

Interface variable holds reference to Interface variable holds reference to object of a class that implements the object of a class that implements the interfaceinterfaceMeasurable x;Measurable x;x = new BankAccount(10000);x = new BankAccount(10000);

x = new Coin(0.1, "dime");x = new Coin(0.1, "dime");

Note that the object to which x refers Note that the object to which x refers doesn't have type Measurable; doesn't have type Measurable; the type of the object is some class that the type of the object is some class that

implements the Measurable interface implements the Measurable interface

Page 32: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

Purpose of Purpose of PolymorphismPolymorphism

You can call any of the interface You can call any of the interface methods:methods:double m = x.getMeasure(); double m = x.getMeasure();

Which method is called? Which method is called?

Depends on the actual object.  Depends on the actual object.  If x refers to a bank account, calls If x refers to a bank account, calls BankAccount.getMeasure() BankAccount.getMeasure()

If x refers to a coin, calls If x refers to a coin, calls Coin.getMeasure()Coin.getMeasure()

Page 33: Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert

PolymorphismPolymorphism

Polymorphism (many shapes): Behavior Polymorphism (many shapes): Behavior can vary depending on the actual type of can vary depending on the actual type of an object an object The property the we can call The property the we can call x.getMeasure()x.getMeasure()

with multiple contexts is an instance of with multiple contexts is an instance of polymorphismpolymorphism

Called Called late bindinglate binding: resolved at runtime : resolved at runtime

Different from overloading; overloading is Different from overloading; overloading is resolved by the compiler (resolved by the compiler (early bindingearly binding) )