Polymorphism and interfaces Horstmann ch 4
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
Displaying an image JOptionPane.showMessageDialog(null, ”Welcome!”);
Displaying an image Use image from file JOptionPane.showMessageDialog( null, ”Welcome!”, ”Message”, JOptionPane.INFORMATION_MESSAGE, new ImageIcon(”au.jpg”));
Displaying an image Draw image JOptionPane.showMessageDialog( null, ”Welcome!”, ”Message”, JOptionPane.INFORMATION_MESSAGE, new CarIcon(100));
Interface How can an image from a file be used in the same way as an image specified by a drawing algorithm? By using an interface! Interface Icon abstracts the relevant properties public interface Icon { int getIconWidth(); int getIconHeight(); void paintIcon(Component c, Graphics g, int x, int y); } Interface contain no implementation of methods
Interface JOptionPane.showMessageDialog( null, ”Welcome!”, ”Message”, JOptionPane.INFORMATION_MESSAGE, new CarIcon(100)); public static void showMessageDialog( Component parentComponent, Objekt message, String title, int messageType, Icon icon) showMessageDialog knows about au-logo and car picture ONLY as something implementing interface Icon
Interface Implementing class must supply implementation of all methods public class CarIcon implements Icon { public int getIconWidth() {... } public int getIconHeight() {... } public void paintIcon(Component c, Graphics g, int x, int y) {... } }
QUIZ Which assertions are true? 1.none 2.A 3.B 4.C 5.A, B 6.A, C 7.B, C 8.A, B, C 9.I don’t know A.An interface specifies method headers B.An interface specifies method bodies C.Comparable implements interface String
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
Decoupling showMessageDialog expects an Icon object showMessageDialog need not know whether the actual type of the object is CarIcon or ImageIcon or …
Polymorphic variable public static void showMessageDialog( …, Icon anIcon) showMessageDialog doesn't know which icon is passed –ImageIcon ? –MarsIcon ? –... ? The actual type of anIcon is not Icon There are no objects of type Icon anIcon belongs to a class that implements Icon That class defines methods getIconWidth, getIconHeight, etc.
Method Polymorphism public static void showMessageDialog( …, Icon anIcon) showMessageDialog must compute size of dialog width = icon width + message size + blank size How do we know the icon width? int width = anIcon.getIconWidth(); Which getIconWidth method is called? Could be –MarsIcon.getIconWidth –ImageIcon.getIconWidth –... Depends on object to which anIcon reference points, e.g. showMessageDialog(..., new MarsIcon(50)) Polymorphism: Select different methods according to actual object type
QUIZ Which lines result in errors? 1.none 2.a 3.b 4.a+b 5.I don’t know Sad s; s = new Choleric(); a) s.cry(); b) s.laugh();
QUIZ Which lines result in errors? 1.none 2.a 3.b 4.c 5.a+b 6.a+c 7.b+c 8.a+b+c 9.I don’t know Sad s; Choleric c; c = new Choleric(); a) s = c; b) c = s; c) c = (Choleric) s;
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
Example: sorting Sort by name –AntiChrist, 108 min –Gran Torino, 116 min –Mænd der hader kvinder, 155 min –Slumdog Millionaire, 120 min Sort by duration –AntiChrist, 108 min –Gran Torino, 116 min –Slumdog Millionaire, 120 min –Mænd der hader kvinder, 155 min
Comparable interface type Collections has static sort method. For a being an array list Collections.sort(a); Objects in list must implement the Comparable interface type public interface Comparable { int compareTo(T other); } object1.compareTo(object2) returns –Negative number if object1 less than object2 –0 if objects identical –Positive number if object1 greater than object2 How can we sort Films by both name and length? Can't implement Comparable twice! dIntProg
Comparator interface type Comparator interface type gives added flexibility public interface Comparator { int compare(T object1, T object2); } Comparator object is a function object Pass comparator object to sort: Collections.sort(list, comp);
Strategy ArrayList films =... ; Comparator comp1 = new NameComp(); Collections.sort(films, comp1); Comparator comp2 = new LenghtComp(); Collections.sort(films, comp2);
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
Anonymous Classes No need to name classes that are used only once Comparator comp = new Comparator () { public int compare(Film f1, Film f2) { return f1.getName().compareTo(f2.getName()); } }; Same as Comparator comp = new NameComp(); public class NameComp implements Comparator { public int compare(Film f1, Film f2) { return f1.getName().compareTo(f2.getName()); }
Anonymous Classes Commonly used in factory methods: public static Comparator comparatorByName() { return new Comparator () { public int compare(Film c1, Film c2) {...} }; } Collections.sort(a, Film.comparatorByName()); Neat arrangement if multiple comparators make sense (by name, by length,...)
QUIZ Which lines result in errors? 1.None (or missing code) 2.a 3.b 4.a+b 5.I don’t know Sad s; a) s = new Sad() { b) public void laugh() {...} };
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
Frames Frame window has decorations –title bar –close box –provided by windowing system JFrame frame = new JFrame(); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);
Adding Components Construct components JButton helloButton = new JButton("Say Hello"); Set frame layout frame.setLayout(new FlowLayout()); Add components to frames frame.add(helloButton);
User Interface Actions Add listener object(s) to button public interface ActionListener { void actionPerformed(ActionEvent event); } Listeners are notified when button is clicked
User Interface Actions helloButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { textField.setText("Hello, World"); } ); When button is clicked, text field is set
User Interface Actions Constructor attaches listener: helloButton.addActionListener(listener); Button remembers all listeners When button clicked, button notifies listeners listener.actionPerformed(event); Listener sets text of text field textField.setText("Hello, World!");
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
Accessing Variables from Enclosing Scope Remarkable: Inner class can access variables from enclosing scope e.g. textField Can access enclosing instance fields, local variables Local variables must be marked final final JTextField textField =...;... helloButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { textField.setText("Hello, World"); } ); final
QUIZ public class Quiz { private final TextField display = …; public ActionListener createButtonListener( final String message) { final String prefix = “NOTE: “; return new ActionListener() { public void actionPerformed(ActionEvent event) { display.setText(prefix + message); } }; } 1.None 2.a 3.b 4.c 5.a, b 6.a, c 7.b, c 8.a, b, c 9.I don’t know a b c Which of the 3 ”final” can be removed without errors?
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
Timers Supply delay, action listener ActionListener listener =...; final int DELAY = 1000; // 1000 millisec = 1 sec Timer t = new Timer(DELAY, listener); t.start(); Action listener called when delay elapsed
Defining a New Interface Type Use timer to move car shapes Draw car with CarShape Two responsibilities: –Draw shape –Move shape Define new interface type MoveableShape
Implementing the Animation
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
Graphics in Java… How is the car Icon drawn? paintIcon method receives graphics context of type Graphics Actually a Graphics2D object in modern Java versions public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2 = (Graphics2D)g;... } Can draw any object that implements Shape interface Shape s =...; g2.draw(s);
Drawing Rectangles Rectangle2D.Double constructed with –top left corner –width –height g2.draw( new Rectangle2D.Double(x, y, width, height) );
Drawing Ellipses For Ellipse2D.Double, specify bounding box
Drawing Line Segments Point2D.Double is a point in the plane Line2D.Double joins two points Point2D.Double start = new Point2D.Double(x1, y1); Point2D.Double end = new Point2D.Double(x2, y2); Shape segment = new Line2D.Double(start, end); g2.draw(segment);
Relationship Between Shape Classes
Drawing Text g2.drawString("Message", x, y); x, y are base point coordinates
Filling Shapes Fill interior of shape g2.fill(shape); Set color for fills or strokes: g2.setColor(Color.red); Program that draws car (uses class CarIcon )