Title: Polymorphism via Interfaces and Java's Collection Framework
1Polymorphism via Interfaces and Java's Collection
Framework
2Outline
- Polymorphism
- Review the Java interface construct
- Java's new Comparable interface
- Java's Collections Framework
3Polymorphism http//www.webopedia.com/TERM/p/polym
orphism.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
4Polymorphism from mercer
- To understand polymorphism, take an example of a
typical workday in an office. 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.
5Polymorphism
- 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 or
Java. Marty went back to work on the index of his
new book. And Kim cleaned up the pastries.
6Polymorphic Messages
- 9 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,
7Polymorphism
- 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
- interfaces
- Collections.sort sends compareTo messages to
objects that must have implemented Comparable
8Polymorphism
- 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)
- aHashSet.add(anObject)
- aTreeSet.add(anObject)
9The 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 gt 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
10Old MacDonald had a farm
- An interface, a reference type, can have
- static variables and method headings with
- public int size() // no
- Methods are implemented by classes
- Example interface
- public interface BarnyardAnimal
- public String sound()
-
11Multiple classes implement the same interface
- To implement an interface, classes must have all
methods specified as given in the interface - public class Cow implements BarnyardAnimal
- public String sound()
- return "moo"
-
-
- public class Chicken implements BarnyardAnimal
- public String sound()
- return "cluck"
-
-
12The same interface type
- BarnyardAnimal aCow new Cow()
- BarnyardAnimal aChicken new Chicken()
- assertEquals(_______, aCow.sound())
- assertEquals(_______, aChicken.sound())
- Fill in the blanks so the assertions pass
- Can store references to a Cow and a Chicken into
a reference variable of type BarnyardAnimal
13The Comparable interface a less silly
example
- 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
14Implementing Comparable
- Any type can implement Comparable to determine if
one object is less than, equal or greater than
another - public interface ComparableltTgt /
- 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)
-
15Code Demo
- Have DayCounter implement ComparableltTgt so today
is less than tomorrow and today is equal to
today, no matter what millisecond created. - First consider the GregorianCalendar compareTo on
the next slide
16With java's GregorianCalendar, milliseconds count
- _at_Test
- public void todayLessThanToday()
- GregorianCalendar today
- new GregorianCalendar()
- try
- Thread.sleep(1000) // Pause for 1 second
-
- catch (InterruptedException e)
-
- GregorianCalendar todayAgain
- new GregorianCalendar()
- assertEquals(-1, today.compareTo(todayAgain))
17Desired DayCounter Behavior
- _at_Test
- public void TodayIsNOTLess ()
- // With no arguments, today will be the //
day this it's constructed - DayCounter today new DayCounter()
- try
- Thread.sleep(1000) // Pause for 1 second
- catch (InterruptedException e)
-
- DayCounter todayAgain new DayCounter()
- assertEquals(0, today.compareTo(todayAgain))
18Java's Collection Framework
- Collection framework
- Unified architecture for representing and
manipulating collections - Java's collection framework contains
- Interfaces (ADTs) specification not
implementation - Concrete implementations as classes
- Polymorphic Algorithms to search, sort, find,
shuffle, ... - The algorithms are polymorphic
- the same method can be used on many different
implementations of the appropriate collection
interface. In essence, algorithms are reusable
functionality.
19Collection interfaces in java.util
Image from the Java Tutorial
20Abstract 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?
21Collection 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
- Java 5 has concrete collection classes
- StackltEgt
- ArrayListltEgt, LinkedListltEgt
- LinkedBlockingQueueltEgt, ArrayBlockingQueueltEgt
- HashSetltEgt, TreeSetltEgt
- TreeMapltK,Vgt, HashMapltK,Vgt
22Common 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
23ListltEgt, an ADT written as a Java interface
- ListltEgt 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 - ArrayListltEgt
- LinkedListltEgt
- VectorltEgt
24- import java.util. // For List, ArrayList,
Linked ... - import static org.junit.Assert.
- import org.junit.Test
- public class ThreeClassesImplementList
- _at_Test
- public void showThreeImplementationsOfList()
- // Interface name List
- // Three classes that implement the List
interface - ListltStringgt bigList new ArrayListltStringgt()
- ListltStringgt littleList new
LinkedListltStringgt() - ListltStringgt sharedList new
VectorltStringgt() - // All three have an add method
- bigList.add("in array list")
- littleList.add("in linked list")
- sharedList.add("in vector")
25Iterators
- Iterators provide a general way to traverse all
elements in a collection - ArrayListltStringgt list new
ArrayListltStringgt() - list.add("1-FiRsT")
- list.add("2-SeCoND")
- list.add("3-ThIrD")
-
- IteratorltStringgt itr list.iterator()
- while (itr.hasNext())
- System.out.println(itr.next().toLowerCase())
-
Output 1-first 2-second 3-third
26Enhanced 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 " ")
27Can'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
- ArrayListltGregorianCalendargt dates
- new ArrayListltGregorianCalendargt()
- dates.add(new GregorianCalendar()) // Okay
- dates.add("String not a GregorianCalendar") //
Error - ArrayListltIntegergt ints new ArrayListltIntegergt()
- ints.add(1) // Okay. Same as add(new
Integer(1)) - ints.add("Pat not an int")) // Error
28TreeSet implements Set
- SetltEgt An interface for collections with no
duplicates. More formally, sets contain no pair
of elements e1 and e2 such that e1.equals(e2) - TreeSetltEgt 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 ComparableltTgt
29Set and SortedSet
- The SetltEgt interface
- add, addAll, remove, size, but no get!
- Two classes that implement SetltEgt
- 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(), SortedSetltEgt tailSet(EÂ fromElement), - SortedSetltEgt headSet(EÂ fromElement), E
last(), SortedSetltEgt subSet(EÂ fromElement,
EÂ toElement)
30TreeSet elements are in order
- SetltStringgt names new TreeSetltStringgt()
- names.add("Sandeep")
- names.add("Chris")
- names.add("Kim")
- names.add("Chris") // not added
- names.add("Devon")
- for (String name names)
- System.out.println(name)
- Output?
- Change to HashSet
31The 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
32Map Operations
- Java's HashMapltK, Vgt
- 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. - CollectionltVgt values()
- get a collection you can iterate over
33Code Demo Rick Put in a file named
HashMapDemo.java
- Add some mappings to a HashMap and iterate over
all elements with CollectionltVgt values() and all
keys with SetltKgt keySet()
34QueueltEgt
- 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
35ArrayBlockingQueueltEgt a FIFO queue
- ArrayBlockingQueueltDoublegt numberQ
- new ArrayBlockingQueueltDoublegt(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())
36Algorithms
- 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
37This should run
- _at_Test
- public void testEquals()
- DayCounter today new DayCounter(2007, 8, 28)
- DayCounter nextWeek new DayCounter(2007, 4,
28) - assertTrue(today.equals(today))
- assertFalse(today.equals(nextWeek))
- assertFalse(nextWeek.equals(today))
- assertFalse(nextWeek.equals(null))
- assertFalse(nextWeek.equals("Not a Counter"))
- DayCounter d3 new DayCounter(2006, 6, 14)
- DayCounter d4 new DayCounter(2005, 9, 30)
- DayCounter d5 new DayCounter(2006, 9, 30)
- ArrayListltDayCountergt dates new
ArrayListltDayCountergt() - dates.add(today)
- dates.add(nextWeek)
- dates.add(d3)
- dates.add(d4)
38If time permits. 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 much better
- and it will be demonstrated Thursday
39- 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)