Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Interfaces and Polymorphism: A Java Approach for CMPU-101 Students - Prof. Marc L. Smith, Study notes of Computer Science

A chapter from the cmpu-101 course at vassar college, focusing on interfaces and polymorphism in java. It covers the concept of interfaces, their two meanings, implementing interfaces, and the benefits of using interfaces. Examples and code snippets to illustrate the concepts.

Typology: Study notes

Pre 2010

Uploaded on 08/18/2009

koofers-user-ujd-1
koofers-user-ujd-1 🇺🇸

10 documents

1 / 7

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Chapter 15
Interfaces & Polymorphism
CMPU-101: Problem-Solving and Abstraction
Marc Smith
Vassar College
Spring 2007
2
Plan
Comparable interface
Talker interface
Polymorphism
Passing methods using polymorphism
Produce tables & bar graphs
3
The Two Meanings of "Interface"
1 — The set of public methods offered by a class. For
example, the classes listed in the Java API list their
public methods.
Should allow one to change the implementation
without changing the interface.
2 — A named set of public methods which may be offered
by any number of classes.
A class may implement an interface if it offers the
methods promised by that interface.
4
Musical Instruments
CanPlayNotes interface:
Xylophone — strike the key with a mallet
Violin — finger and then bow or pluck
Flute — finger and then blow air
Piano — strike the key with a finger
All instruments can play notes, but they do it in different
ways.
Their similarities are expressed in an interface and their
differences in the way they play notes.
5
The Comparable Interface
Requires only one method to be declared in classes that
implement this interface:
int compareTo(Object)
o1.compare To(o2) < 0
o1 < o 2
o1.compar eTo(o2) == 0
o1 = o 2
o1.compare To(o2) > 0
o1 > o 2
6
Prog1501
Compare Two Students
while ( true )
{
System.out.println();
Student s1 = Student.read(System.out,kb);
Student s2 = Student.read(System.out,kb);
int compare = s1.compareTo(s2);
System.out.println("\ns1.compareTo(s2) ==> " +
compare);
}
pf3
pf4
pf5

Partial preview of the text

Download Interfaces and Polymorphism: A Java Approach for CMPU-101 Students - Prof. Marc L. Smith and more Study notes Computer Science in PDF only on Docsity!

Chapter 15

Interfaces & Polymorphism

CMPU-101: Problem-Solving and Abstraction Marc Smith

Vassar College Spring 2007

Plan

Comparable interface

Talker interface

Polymorphism

Passing methods using polymorphism

Produce tables & bar graphs

The Two Meanings of "Interface"

1 — example, the classes listed in the Java API list their The set of public methods offered by a class. For

public methods. Should allow one to change the implementation

without changing the interface.

2 — by any number of classes. A named set of public methods which may be offered

A methods promised by that interface. class may implement an interface if it offers the

Musical Instruments

CanPlayNotes Xylophone — interface: strike the key with a mallet

V Fiolinlute — — finger and then blow air finger and then bow or pluck

Piano — strike the key with a finger

A ways.ll instruments can play notes, but they do it in different

T differences in the way they play notes.heir similarities are expressed in an interface and their

The Comparable Interface

Requires only one method to be declared in classes that implement this interface:

int compareTo(Object)

o^ o 11 ..ccoommppaarreeTToo((oo 22 )) =<=^00 oo^11 <=^ oo^22 o 1 .compareTo(o 2 ) > 0 o 1 > o 2

Compa^ Prer oTgw^1 o^5 S^0 t^1 udents

while ( true ) {

System.out. Student s1 = Student.read(System.out,kb);println();

Student s2 = Student.read(System.out,kb); int compare = s1.compareTo(s2);

System.out.println("\ns1.compareTo(s2) ==> " + compare);

Implementing an interface is a contract...

class Student implements Comparable

W clahsast iSf t…udent fails to contain int compareTo(Object)?

(^2) F (^) ieler:r o/Urss (^) eforusn/jedn:ny/Desktop/cs 101 /lect 15 /Chapter 15 programs/Prog 1501 .java [line: 22 ] E s lorycrmoarbti:oo cln a:n: cnmlaoestt (^) shfi onSddt (^) u (^) csdoyemmntbpoarleTo(Student) F Eirlreo: c (^) r/:oU Smsteuprdasre/ejenTnt (^) onis(yj (^) an/Dvoaet. salakbntsogtp.rO/accbstj (^1) ea (^0) cn (^1) td)/l iednco tjea (^1) sv 5 / (^) anC.olhatan opgvt.Ceerro (^1) rm (^5) idpper (^) aoargbarsbatlremasc/tP mroegth (^15) o (^0) d 1 .java [line: 29 ]

8

Student Class compareTo method

public { int compareTo ( Object o )

Student that = (Student) o; return ( this.grade - that.grade );

b^ S i t l u l de n ( t^ 9 s^1 8^ ) s S u tu e d e ( nt 8^ s 0^2 )^ re 1 su 8 lt

b biillll (( 9988 )) saanlnliye (( 19080 )) - 02

Prog 1502

i Snty sctoemmp.oauret. p=r isn 1 t(."c\onm" +p asr 1 e)T;o(s 2 );

if ( Scoymstpeamre.o >u t 0 .p )ri n{t(" is greater than ");

} else if ( compare < 0 ) {

}^ System.out.print("^ is^ less^ than^ "^ );

else S y{stem.out.print(" equals ");

} System.out.println(s 2 );

public boolean { isLessThan ( Student that )

}^ return this.compareTo(that) < 0;

public boolean { isEqualTo ( Student that )

}^ return this.compareTo(that) == 0;

public boolean { isGreaterThan ( Student that )

}^ return this.compareTo(that) > 0;

What Good Are Interfaces?

For one thing, they allow us to use handy API methods:

Arrays.sort(a, 0 ,used);

S moarntsn ethr es pinepcuifti eadrr bayy ath fero cmom ppoasriteioTno 0 m teot hpoods it)ion used ( in the

What kin Sort is a static method that works on an arrayd of method is sort?

of objects that implement the comparable interface.
The sort method is overloaded in 18 different ways to sort any array of primitive type, too.

Prog 1503 — Sorting an Array

In class Section : public void sort() { Arrays.sort(a, 0 ,used); }

class Human implements Talker {

private String name;

public Human ( String name ) {

}^ this.name = name;

public void talk ( { PrintStream ps )

}^ ps.println("My name is " + name + ".");

class Mime implements Talker {

private String name;

public Mime ( String name ) {

}^ this.name = name;

public void talk ( { PrintStream ps )

}^ ps.println("");

Variables Can Be Declared as Type Talker

Talker t; t = new Dog();

t = new Cat(); t = new Mime("Marcel");

t = new Human("Ashton");

This violates our prior belief that a reference variable, once declared, can
only refer to instances of a single type.
What other lies are we guilty of????
This shows us that a variable may be different from its actual ’s d type eclared type

Code:

t = new Dog(); t.talk();

t = new Cat(); t.talk();

t = new Mime("Marcel"); t.talk();

t = new Human("Ashton"); t.talk();

Output:

Woof!

Meow!

My name is Ashton.

Notice that the same variable, t, refers to different types of objects at different times…

Arrays Can Be Declared as Type Talker

Talker[] a = new Talker[5];

t[0] = new Dog(); t[1] = new Cat();

t[2] = new Human("Bill"); t[3] = new Mime("Marcel");

t[4] = new Human("Sue");

But wait, did we tell you that arrays can contain
only a single type??
Aaaagh! Another lie!!

Array of CanPlayNotes

CanPlayNotes quartet[0] = new Violin([] quartet = new CanPlayNotes[4];…);

quartet[1] = new Violin( quartet[2] = new Viola(……));;

quartet[3] = new Cello(…);

Polymorphism

Talker t; t = new Dog();

t = new Cat(); t = new Mime("Marcel");

t = new Human("Ashton");

From the Greek describes phenomenon where a “many-shaped”,
single variable can be set equal to different object types

Polymorphism

Talker[] a = new Talker[5];

a[0] = new Dog(); a[1] = new Cat();

a[2] = new Human("Bill"); a[3] = new Mime("Marcel");

a[4] = new Human("Sue");

Polymorphism

for ( a[i].talk(System.out); int i = 0 ; i < 5 ; i++ )

Woof! Meow!

My name is Bill.

My name is Sue.

Most objects are bound to a particular type at compile time so the compiler
can determine the method being called. This is called “Early binding”
With polymorphism, occur. In this case, the exact method “Late binding” can
being called is not determined until run time.

Before Polymorphism

for ( { int i = 0 ; i < 5 ; i++ )

if else if ( a[i] ( a[i] iinstanceofnstanceof DCog )at ) ……

else if ( a[i] else if ( a[i] iinstanceofnstanceof HMuman )ime ) … …

Instead, replace if-else statements with a single a[i].talk();

The keyword asks if a particular object “instanceof”
“is-a” particular type

A C Mlausltsip Clea nIn tIemrfpalecmesent

class Copier implements Printer, Scanner

Prog1505 The class that implements multiple

interfaces must provide implementations of all prototype methods from each
interface it implements.

Passing One Method

to Another Method

makeGraph

method limits

Interfaces and GUIs

Interfaces we saw when programming GUIs:

1. ActionListener public void actionPerformed: requires (ActionEvent e)

2. MouseListener public void mousePressed: requires (MouseEvent m)

public void public void mmouseClickedouseReleased(M(ouseEventMouseEvent m )m)

public void public void mmouseEnteredouseExited(M(MouseEventouseEvent m m))

0123 .... 0000 1230222 .... 0060 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Bar Graphs

Prog 1507 — Bar Graph

for ( { int i = 0 ; i < MAXROWS ; i++ )

System.out. int width = (ipntrintf)f.v alueAt("%5.1f %5.1f", (double)i, f.valueAt(i));(i);

if ( width > MAXWIDTH ) width = MAXWIDTH;

if ( width < 0 ) width = 0; for ( int j = 0 ; j < width ; j++ )

System.out.^ System.out.print("+");println();