3-1 polymorphism with java interfaces rick mercer
TRANSCRIPT
3-1
Polymorphism with Java Interfaces
Rick Mercer
3-2
Outline
Describe PolymorphismShow 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-3
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-4
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-5
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-6
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-7
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<T>
3-8
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-9
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-10
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 classesExample interface :
public interface ActionListener { public void actionPerformed(ActionEvent theEvent);}
3-11
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-12
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<BankAccount>, Serializable
Notice that a class can implement >1 interfaces More on Serializable later
3-13
The Comparable interfaceA 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-14
Implementing Comparable
Any type can implement Comparable to determine if one object is less than, equal or greater than another
public interface Comparable<T> { /** * 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-15
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 comparator<T> { public int 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<BankAccount> idComparator = new ByID();Collections.sort(accounts, idComparator);
More on Collections.Sort later
3-16
class OurIcon implements Icon
TBA???
3-17
Playing an Audio Fileusing an interface
interface AudioClip has 3 methods— loop, play, stop
The Applet class implements AudioClipSupports 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-18
AudioClip audioClip = null;URL url = null;
// This assumes songs are in a folder named songfile// Need "file:" unless you are reading it over the webString 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-19
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-20
Collection interfaces in java.util
Image from the Java Tutorial
3-21
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-22
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<E>— ArrayList<E>, LinkedList<E>— LinkedBlockingQueue<E>, ArrayBlockingQueue<E>— HashSet<E>, TreeSet<E>— TreeMap<K,V>, HashMap<K,V>
3-23
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-24
List<E>, an ADT written as a Java interface
List<E>: 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<E>— LinkedList<E>— Vector<E>
3-25
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<String> bigList = new ArrayList<String>(); List<String> littleList = new LinkedList<String>(); List<String> sharedList = new Vector<String>();
// 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-26
Iterators
Iterators provide a general way to traverse all elements in a collection
ArrayList<String> list = new ArrayList<String>(); list.add("1-FiRsT"); list.add("2-SeCoND"); list.add("3-ThIrD"); Iterator<String> itr = list.iterator(); while (itr.hasNext()) { System.out.println(itr.next().toLowerCase()); }
Output1-first2-second3-third
3-27
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-28
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<GregorianCalendar> dates =
new ArrayList<GregorianCalendar>();
dates.add(new GregorianCalendar()); // Okay
dates.add("String not a GregorianCalendar"); // Error
ArrayList<Integer> ints = new ArrayList<Integer>();
ints.add(1); // Okay. Same as add(new Integer(1))
ints.add("Pat not an int")); // Error
3-29
Algorithms
Java has polymorphic algorithms to provide functionality for different types of collections— Sorting (e.g. sort)— Shuffling (e.g. shuffle)— Routine Data Manipulation (e.g. reverse, addAll)— Searching (e.g. binarySearch)— Composition (e.g. frequency)— Finding Extreme Values (e.g. max)
Demo a few with ArrayList— Override toString and equals for DayCounter
3-30
TreeSet implements Set
Set<E> An interface for collections with no duplicates. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2)
TreeSet<E>: 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<T>
3-31
Set and SortedSet
The Set<E> interface— add, addAll, remove, size, but no get!
Two classes that implement Set<E>— 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 fromElement), E last(), SortedSet<E> subSet(E fromElement, E toElement)
3-32
TreeSet elements are in order
Set<String> names = new TreeSet<String>();names.add("Sandeep");names.add("Chris");names.add("Kim");names.add("Chris"); // not addednames.add("Devon");
for (String name : names) System.out.println(name);
Output?Change to HashSet
3-33
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 valueThe keys must be unique
— the values need not be unique— put destroys one with same key
3-34
Map Operations
Java's HashMap<K, V>— 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<V> values() • get a collection you can iterate over
3-35
Code Demo Rick: Put in a file named HashMapDemo.java
Add some mappings to a HashMap and iterate over all elements with Collection<V> values() and all keys with Set<K> keySet()
3-36
Queue<E>
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-37
ArrayBlockingQueue<E> a FIFO queue
ArrayBlockingQueue<Double> numberQ = new ArrayBlockingQueue<Double>(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());