PolymorphismInterfacesCollections

Download Report

Transcript PolymorphismInterfacesCollections

Polymorphism with Java Interfaces

Rick Mercer 3-1

Outline

 Describe Polymorphism  Show a few ways that interfaces are used — Respond to user interaction with a GUI with

ActionListener

— Compare objects with

Comparator

— — Tag types to have writeable/readable objects with

Serializable

Create our own icons with

Icon

— Play audio files with

AudioClip

— Show polymorphic algorithms on

List

3-2

Polymorphism

http://www.webopedia.com/TERM/p/polymorphism.html

 In general, polymorphism is the ability to appear in many forms  In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type (class)  Polymorphism is considered to be a requirement of any true object-oriented programming language 3-3

Polymorphism

from mercer

To understand polymorphism, take an example of a workday at Franklin, Beedle, and Associates. Kim brought in pastries and everyone stood around chatting. When the food was mostly devoured, Jim, the president of the company, invited everyone to “Get back to work.” Sue went back to read a new section of a book she was editing. Tom continued laying out a book. Stephanie went back to figure out some setting in her word-processing program. Ian finished the company catalog. 3-4

Polymorphism

Jeni met with Jim to discuss a new project. Chris began contacting professors to review a new manuscript. And Krista continued her Web search to find on whether colleges are using C++, Python, or Java. Marty went back to work on the index of his new book. Kim cleaned up the pastries. Rick's was just visiting so he went to work on the remaining raspberries.

3-5

Polymorphic Messages

 10 different behaviors with the same message!  The message “Get back to work” is a

polymorphic message

— a message that is understood by many different types of object (or employees in this case) — but responded to with different behaviors based on the type of the employee: Editor, Production, Marketing, … 3-6

Polymorphism

 Polymorphism allows the same message to be sent to different types to get different behavior  In Java, polymorphism is possible through — inheritance • Override

toString

to return different values that are textual representations of that type.

— interfaces •

Collections.sort

sends

compareTo

messages to objects that must have implemented

Comparable

3-7

Polymorphism

 The runtime message finds the correct method — same message can invoke different methods — the reference variable knows the type

aString.compareTo(anotherString) anInteger.compareTo(anotherInteger) aButton.actionPerformed(anEvent) aTextField.actionPerformed(anEvent) aList.add(anObject) aHashSet.add(anObject)

3-8

The Java Interface

 An interface describes a set of methods — NOT allowed: constructors, instance variables — static variables and methods are allowed  Interfaces must be implemented by a class — 646 classes implement >= 1 interfaces (in '02)  Typically, two or more classes implement the same interface — Type guaranteed to have the same methods — Objects can be treated as the same type — May use different algorithms / instance variables 3-9

An interface we'll use soon

 An

interface

, a reference type, can have —

static

variables and method headings with

;

public int size(); // no { }  Methods are implemented by 1 or more classes  Example

interface

:

public interface ActionListener { public void actionPerformed(ActionEvent theEvent); }

3-10

Multiple classes implement the same interface

 To implement an

interface

, classes must have all methods specified as given in the interface

private class Button1Listener implements ActionListener { } public void actionPerformed(ActionEvent theEvent) {

// Do this method when button1 is clicked

} private class Button2Listener implements ActionListener { } public void actionPerformed(ActionEvent theEvent) {

// Do this method when button2 is clicked

}

More on ActionListener later

3-11

interface Serializable

 Classes that implement

interface Serializable

can have their objects written to and read from streams with

writeObject

and

readObject

 It is just a tag—no methods

public class BankAccount implements Comparable, Serializable

 Notice that a class can implement >1 interfaces

More on Serializable later

3-12

The Comparable interface

A review for most  Can assign an instance of a class that implements and interface to a variable of the interface type

Comparable str = new String("abc"); Comparable acct = new BankAccount("B", 1); Comparable day = new Date();

 Some classes that implement

Comparable BigDecimal BigInteger Byte ByteBuffer Character CharBuffer Charset CollationKey Date Double DoubleBuffer File Float FloatBuffer IntBuffer Integer Long LongBuffer ObjectStreamField Short ShortBuffer String URI

 Comparable defines the "natural ordering" for collections 3-13

Implementing Comparable

 Any type can implement Comparable to determine if one object is less than, equal or greater than another

public interface Comparable { } /** * Return 0 if two objects are equal; less than * zero if this object is smaller; greater than * zero if this object is larger.

*/ public int compareTo(T other);

3-14

interface comparator

/** * Compares its two arguments for order. Returns a * negative integer, zero, or a positive integer as the * first argument is less than, equal to, or greater * than the second argument.

Equals not shown here

*/ public interface public int comparator { compareTo(T other); }

 Can specify sort order by objects. In the code below — What class needs to be implemented?

— What interface must that class implement?

Comparator idComparator = new Collections.sort(accounts, idComparator); ByID();

More on Collections.Sort later

3-15

class OurIcon implements Icon

TBA???

3-16

Playing an Audio File using an interface

 interface AudioClip has 3 methods — loop, play, stop  The Applet class implements AudioClip  Supports recording, playback, and synthesis of sampled audio and Musical Instrument Digital Interface (MIDI) sequences — Can play .au, .aif, .wav, .midi (sort of) — For mp3s, need something more complex • We'll see such a libraty later semester 3-17

AudioClip audioClip = null ; URL url = null ; // This assumes songs are in a folder named songfile // Need "file:" unless you are reading it over the web String baseFolder = "file:" + System.getProperty( "user.dir" ) + "/songfiles/" ; try { url = new URL(baseFolder + "Dancing_Queen.au" ); audioClip = Applet.newAudioClip(url); } catch (MalformedURLException e) { System.

out

.println( "bad url " + url); } audioClip.play(); JOptionPane.showMessageDialog( null , "End " + url);

3-18

Java's Collection Framework

   — Java's Collection Framework Unified architecture for representing and manipulating collections — Collection framework contains Interfaces (ADTs): specification not implementation — — Concrete implementations as classes Polymorphic Algorithms to search, sort, find, shuffle, ...

— Algorithms are

polymorphic

: the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.

3-19

Collection interfaces in java.util

Image from the Java Tutorial

3-20

Abstract Data Type

 Abstract data type (ADT) is a specification of the behaviour (methods) of a type — Specifies method names to add, remove, find — Specifies if elements are unique, indexed, accessible from only one location, mapped,...

— An ADT shows no implementation • no structure to store elements, no implemented algorithms  What Java construct nicely specifies ADTs? 3-21

Collection Classes

 A collection class the can be instantiated — implements an interface as a Java class — implements all methods of the interface — selects appropriate instance variables  Since Java 5: we have concrete collection classes —

Stack

— — — —

ArrayList

,

LinkedList LinkedBlockingQueue

,

ArrayBlockingQueue HashSet

,

TreeSet TreeMap

,

HashMap

3-22

Common Functionality

 Collection classes often have methods for — Adding objects — Removing an object — Finding a reference to a particular object

find

• can then send messages to the object still in the collection 3-23

List, an ADT written as a Java interface

 List : a collection with a first element, a last element, distinct predecessors and successors — — The user of this interface has precise control over where in the list each element is inserted duplicates that "

equals

" each other are allowed  The List interface is implemented by these three collection classes — ArrayList — LinkedList — Vector 3-24

import java.util.*; // For List, ArrayList, Linked ... import static org.junit.Assert.*; import org.junit.Test; public class ThreeClassesImplementList { @Test public void showThreeImplementationsOfList() { // Interface name: List // Three classes that implement the List interface: List bigList = new ArrayList(); List littleList = new List sharedList = new LinkedList(); Vector(); // All three have an add method bigList.add( "in array list" ); littleList.add( "in linked list" ); sharedList.add( "in vector" ); } } // All three have a get method assertEquals( "in array list" , bigList.get(0)); assertEquals( "in linked list" , littleList.get(0)); assertEquals( "in vector" , sharedList.get(0));

3-25

Iterators

 Iterators provide a general way to traverse all elements in a collection

ArrayList list = new ArrayList(); list.add("1-FiRsT"); list.add("2-SeCoND"); list.add("3-ThIrD"); Iterator itr = list.iterator(); while (itr.hasNext()) { System.out.println(itr.next().toLowerCase()); }

Output

1-first 2-second 3-third

3-26

Newest way to visit elements: Java's Enhanced for Loop

 The for loop has been enhanced to iterate over collections  General form for (Type element : collection) {

element is the next thing visited each iteration

} for (String str : list) { System.out.println(str + " "); }

3-27

Can't add the wrong type

 Java 5 generics checks the type at compile time — See errors early--a good thing — "type safe" because you can't add different types

ArrayList dates = new ArrayList(); dates.add( new GregorianCalendar()); // Okay dates.add( "String not a GregorianCalendar" ); // Error ArrayList ints = new ArrayList(); ints.add(1); // Okay. Same as add(new Integer(1)) ints.add( "Pat not an int" )); // Error

3-28

Algorithms

 Java has

polymorphic

algorithms to provide functionality for different types of collections — Sorting — Shuffling (e.g. sort) (e.g. shuffle) — Routine Data Manipulation — Composition (e.g. frequency) (e.g. reverse, addAll) — Searching (e.g. binarySearch) — Finding Extreme Values (e.g. max)  Demo a few with ArrayList — Override toString and equals for DayCounter 3-29

TreeSet implements Set

 Set An

interface

for collections with no duplicates. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2)  TreeSet : This

class

implements the Set interface, backed by a balanced binary search tree. This class guarantees that the sorted set will be in ascending element order, sorted according to the

natural order

of the elements as defined by Comparable 3-30

Set and SortedSet

 The Set interface — add, addAll, remove, size, but no get!

 Two classes that implement Set — TreeSet: values stored in order, O(log n) — HashSet: values in a hash table, no order, O(1)  SortedSet extends Set by adding methods E

first

(), SortedSet < E >

tailSet

( E fromElement), SortedSet < E >

headSet

( E SortedSet < E >

subSet

( E fromElement), E fromElement, E

last

(), toElement) 3-31

TreeSet elements are in order

Set names = new names.add( "Sandeep" ); names.add( "Chris" ); names.add( "Kim" ); TreeSet(); names.add( "Chris" ); // not added names.add( "Devon" ); for (String name : names) System.

out

.println(name);

 Output?

 Change to HashSet 3-32

The Map Interface (ADT)

 Map describes a type that stores a collection of elements that consists of a

key

and a

value

 A Map associates (maps) a key the it's value  The keys must be unique — the values need not be unique —

put

destroys one with same key 3-33

Map Operations

 Java's HashMap

public V put(K key, V value)

— — — — • associates key to value and stores mapping

public V get(Object key)

• associates the value to which key is mapped or null

public boolean containsKey(Object key)

• returns true if the Map already uses the key

public V remove(Object key)

• Returns previous value associated with specified key, or null if there was no mapping for key.

Collection values()

• get a collection you can iterate over 3-34

Code Demo

Rick: Put in a file named HashMapDemo.java

 Add some mappings to a HashMap and iterate over all elements with

Collection values()

and all keys with

Set keySet()

3-35

Queue

boolean add(E e)

Inserts e into this queue

E element()

Retrieves, but does not remove, the head of this queue

boolean offer(E e)

Inserts e into this queue

E peek()

Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty

E poll()

Retrieves and removes the head of this queue, or returns null if this queue is empty

E remove()

Retrieves and removes the head of this queue 3-36

ArrayBlockingQueue a FIFO queue

ArrayBlockingQueue numberQ = new ArrayBlockingQueue(40); numberQ.add(3.3); numberQ.add(2.2); numberQ.add(5.5); numberQ.add(4.4); numberQ.add(7.7); assertEquals(3.3, numberQ.peek(), 0.1); assertEquals(3.3, numberQ.remove(), 0.1); assertEquals(2.2, numberQ.remove(), 0.1); assertEquals(5.5, numberQ.peek(), 0.1); assertEquals(3, numberQ.size());

3-37