Download presentation
Presentation is loading. Please wait.
Published byToby Russell Modified over 9 years ago
1
Polymorphism and interfaces Horstmann ch 4
2
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
3
Displaying an image JOptionPane.showMessageDialog(null, ”Welcome!”);
4
Displaying an image Use image from file JOptionPane.showMessageDialog( null, ”Welcome!”, ”Message”, JOptionPane.INFORMATION_MESSAGE, new ImageIcon(”au.jpg”));
5
Displaying an image Draw image JOptionPane.showMessageDialog( null, ”Welcome!”, ”Message”, JOptionPane.INFORMATION_MESSAGE, new CarIcon(100));
6
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
7
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
8
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) {... } }
9
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
10
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
11
Decoupling showMessageDialog expects an Icon object showMessageDialog need not know whether the actual type of the object is CarIcon or ImageIcon or …
12
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.
13
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
14
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();
15
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;
16
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
17
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
18
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
19
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);
20
Strategy ArrayList films =... ; Comparator comp1 = new NameComp(); Collections.sort(films, comp1); Comparator comp2 = new LenghtComp(); Collections.sort(films, comp2);
21
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
22
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()); }
23
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,...)
24
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() {...} };
25
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
26
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);
27
Adding Components Construct components JButton helloButton = new JButton("Say Hello"); Set frame layout frame.setLayout(new FlowLayout()); Add components to frames frame.add(helloButton);
28
User Interface Actions Add listener object(s) to button public interface ActionListener { void actionPerformed(ActionEvent event); } Listeners are notified when button is clicked
29
User Interface Actions helloButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { textField.setText("Hello, World"); } ); When button is clicked, text field is set
30
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!");
31
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
32
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
33
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?
34
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
35
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
36
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
37
Implementing the Animation
38
Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java
39
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);
40
Drawing Rectangles Rectangle2D.Double constructed with –top left corner –width –height g2.draw( new Rectangle2D.Double(x, y, width, height) );
41
Drawing Ellipses For Ellipse2D.Double, specify bounding box
42
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);
43
Relationship Between Shape Classes
44
Drawing Text g2.drawString("Message", x, y); x, y are base point coordinates
45
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 )
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.