Title: Presentation 6 Polymorphism through Interfaces
1Presentation 6PolymorphismthroughInterfaces
2From Wepodia http//www.webopedia.com/TERM/p/polym
orphism.html
- polymorphism Generally, 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 or class. More specifically,
it is the ability to redefine methods for derived
classes. For example, given a base class shape,
polymorphism enables the programmer to define
different circumference methods for any number of
derived classes, such as circles, rectangles and
triangles. No matter what shape an object is,
applying the circumference method to it will
return the correct results. Polymorphism is
considered to be a requirement of any true
object-oriented programming language (OOPL).
3From Computing Fundamentals, Mercer
- To understand polymorphism, take an example of
a typical workday in an office. Someone 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 the new edition of a book. Stephanie
went back to figure out some setting in her
word-processing program. Ian finished the company
catalog. - Jeni met with Jim to discuss a new project.
Chris began contacting professors to review a new
manuscript. And Krista continued her Web search
on whether colleges are using C or Java. Rick
went back to work on the index of his new book.
Eight different behaviors from the same message!
The message Get back to work is a polymorphic
messagea message that is understood by many
objects (or employees), but responded to with
different behaviors by different objects (or
employees).
4 How to get polymorphism in Java
- Polymorphism A single name can represent
different behaviors - toString add get iterator compareTo
- In Java, polymorphism is possible through
- inheritance
- interfaces
- JButton and JTextField objects send
actionPerformed messages to different types of
listeners that implement ActionListener - Collections.sort sends compareTo messages to many
different types that implement Comparable
5Polymorphism
- Polymorphism (many forms) allows the same message
to be sent to different types - The runtime message finds the correct method
- same message can invoke different methods
- the reference variable knows the type
- anAccount.toString()
- aString.toString()
- anArrayList.toString()
- aButton.addActionListener(buListener)
- aTextField.addActionListener(tfListener)
- aMenuItem.addActionListener(meListener)
6Polymorphism through Interfaces
- An interface describes a set of methods
- no constructors
- no instance variables
- The interface must be implemented by some class
- 646 java classes implement one or more interfaces
- Multiple classes implement the same interface
- each class is guaranteed to have the same methods
- Let's begin with a simple interface
7Old MacDonald had a farm
- Interfaces, a Java type, have public method
headings followed by semicolons. - no
- No methods are implemented
- the implementing class will do it
- public interface BarnyardAnimal
-
- public String sound()
-
8Multiple classes implement the same interface
- To implement an interface, you must have all
method specified exactly as written in the
interface. - public class Cow implements BarnyardAnimal
-
- public String sound()
-
- return "moo"
-
-
- public class Chicken implements BarnyardAnimal
-
- public String sound()
-
- return "cluck"
-
-
9What is the output?
- BarnyardAnimal animalOne new Cow()
- BarnyardAnimal animalTwo new Chicken()
- System.out.println(animalOne.sound() " "
- animalOne.sound() " here,
and a") - System.out.println(animalTwo.sound() " "
- animalTwo.sound() "
there.") - System.out.println("Here a " animalOne.sound())
- System.out.println("there a "
animalTwo.sound()) - System.out.println("everywhere a "
- animalTwo.sound() " "
- animalTwo.sound() ".")
10Interfaces
- Interfaces are used by Java in many ways
- You class must implement the Comparable interface
to sort and binarySearch elements in a collection - Several classes implement java.util.List
- Can have a List parameter take and ArrayList,
Vector, or LinkedList argument - Must implement an interface to handle events
- Here are three required interfaces
- ActionListener MouseListener KeyListener
11Polymorphism through interfaces
- Can have many different classes of ActionListener
objects - have dozens of classes implement ActionListener
- may need a different method for every button,
text field, or menu item in a GUI for correct
behavior - They all can be treated as ActionListener objects
- They can be passed as arguments to this method
- public void addActionListener(ActionListener ae)
- Adds the specified action listener to receive
action events from JButtons, JTextFields, - Parameters aListener - an instance of a class
that implements the ActionListener interface
12Polymorphism through interfaces
- Each ActionListener object has its own
actionPerformed method - actionPerformed is a polymorphic message
- Graphical components JButton, JTextField,
JMenutItem send the polymorphic message - we don't see them
- Run Polymorphism.java
- which is squeezed into to slide that follows
13- // The three listener clases from page 226 are
included below with public removed so this file
compiles - // Construct a window and add some other
graphical components to it - import java.awt.event.ActionEvent // Need one as
an argument for actionPerformed - import java.awt.event.
- import javax.swing.JButton
- import javax.swing.JOptionPane
- public class Polymorphism
-
- public static void main(String args)
-
- // Construct instances of three classes that
- // can understand the actionPerformed
messages - ActionListener one new ListenerOne()
- ActionListener two new ListenerTwo()
- ActionListener three new ListenerThree()
- // The actionPerformed message needs an
ActionEvent
Run this program to see the polymorphic
actionPerformed message sent to instances of
three different classes that implement
ActionListener. The output shows three different
methods executed with the same message
14Assignment Compatible
- Can assign an instance of a class that implements
and interface to a variable of the interface type - Comparable str new String("abc")
- Comparable anInt new Integer(123)
- Comparable acct new BankAccount("B", 1)
- Comparable day new Date()
- All Known Implementing Classes for Comparable
- BigDecimal BigInteger Byte ByteBuffer
Character CharBuffer Charset CollationKey
Date Double DoubleBuffer File Float
FloatBuffer IntBuffer Integer Long LongBuffer
ObjectStreamField Short ShortBuffer String
URI
15Assignment Compatible
- Can pass instances of a class that implement an
interface to the interface type parameter - addActionListener(ActionListener anyListener)
- addActionListener(new ButtonListener())
- addActionListener(new TextFieldListener())
- Both classes must implement the ActionListener
interface - This design shows a preference to compile time
errors rather than the runtime errors that occur
later when the button sends a message the object
does not understand
16Displaying an Image
- Use JOptionPane to display message
- JOptionPane.showMessageDialog(null, "Hello,
World!") - Note icon to the left
-
17ImageIcon implements Icon
- JOptionPane.showMessageDialog(
- null, "Hello, World!", "Message",
- JOptionPane.INFORMATION_MESSAGE, new
ImageIcon("home34.jpg")) // could be.gif
18Here is the method heading
- public static void showMessageDialog(Component par
entComponent, - Object message,
- String title,
- int messageType,
- Icon icon)
- The 5th parameter is Icon, an interface
- The argument must be an instance of a class that
implements the Icon interface
19Create your own Icon
- See pages 140..145 of Horstmann
- Shows how to paint
- We'll do that Thursday