polymorphism and interfaces horstmann ch 4. outline interface polymorphism function object anonymous...

45
Polymorphism and interfaces Horstmann ch 4

Upload: toby-russell

Post on 01-Jan-2016

230 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Polymorphism and interfaces

Horstmann ch 4

Page 2: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Outline

• Interface• Polymorphism

• Function object

• Anonymous class

• User Interface Action

• Scope of variables

• (Large) example

• Graphics in Java

Page 3: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Displaying an image

JOptionPane.showMessageDialog(null, ”Welcome!”);

Page 4: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Displaying an image

Use image from file

JOptionPane.showMessageDialog(

null,

”Welcome!”,

”Message”,

JOptionPane.INFORMATION_MESSAGE,

new ImageIcon(”au.jpg”));

Page 5: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Displaying an image

Draw image

JOptionPane.showMessageDialog(

null,

”Welcome!”,

”Message”,

JOptionPane.INFORMATION_MESSAGE,

new CarIcon(100));

Page 6: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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

Page 7: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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

Page 8: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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) { . . . }

}

Page 9: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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<String> implements interface String

Page 10: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Outline

• Interface

• Polymorphism• Function object• Anonymous class• User Interface Action• Scope of variables• (Large) example• Graphics in Java

Page 11: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Decoupling

• showMessageDialog expects an Icon object• showMessageDialog need not know whether the actual

type of the object is CarIcon or ImageIcon or …

Page 12: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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.

Page 13: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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

Page 14: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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();

Page 15: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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;

Page 16: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Outline

• Interface• Polymorphism

• Function object• Anonymous class• User Interface Action• Scope of variables• (Large) example• Graphics in Java

Page 17: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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

Page 18: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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<T> { 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

Page 19: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Comparator interface type

• Comparator interface type gives added flexibility public interface Comparator<T> { int compare(T object1, T object2);

}

• Comparator object is a function object

• Pass comparator object to sort:Collections.sort(list, comp);

Page 20: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Strategy

ArrayList<Film> films = . . . ;

Comparator<Film> comp1 = new NameComp();

Collections.sort(films, comp1);

Comparator<Film> comp2 = new LenghtComp();

Collections.sort(films, comp2);

Page 21: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Outline

• Interface• Polymorphism• Function object

• Anonymous class• User Interface Action• Scope of variables• (Large) example• Graphics in Java

Page 22: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Anonymous Classes

• No need to name classes that are used only once

Comparator<Film> comp = newComparator<Film>() { public int compare(Film f1, Film f2) {

return f1.getName().compareTo(f2.getName()); } };

• Same asComparator<Film> comp = new NameComp();

public class NameComp implements Comparator<Film> { public int compare(Film f1, Film f2) { return f1.getName().compareTo(f2.getName()); }}

Page 23: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Anonymous Classes• Commonly used in factory methods:

public static Comparator<Film> comparatorByName() { return new Comparator<Film>() { public int compare(Film c1, Film c2) {...} };}

• Collections.sort(a, Film.comparatorByName()); • Neat arrangement if multiple comparators make sense

(by name, by length, ...)

Page 24: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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() {. . .}

};

Page 25: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Outline

• Interface• Polymorphism• Function object• Anonymous class

• User Interface Action• Scope of variables• (Large) example• Graphics in Java

Page 26: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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);

Page 27: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Adding Components

• Construct componentsJButton helloButton = new JButton("Say Hello");

• Set frame layoutframe.setLayout(new FlowLayout());

• Add components to framesframe.add(helloButton);

Page 28: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

User Interface Actions

• Add listener object(s) to button

public interface ActionListener {

void actionPerformed(ActionEvent event);

}

• Listeners are notified when button is clicked

Page 29: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

User Interface Actions

helloButton.addActionListener(newActionListener() {

public void actionPerformed(ActionEvent event) { textField.setText("Hello, World"); } });

• When button is clicked, text field is set

Page 30: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

User Interface Actions

• Constructor attaches listener:helloButton.addActionListener(listener);

• Button remembers all listeners

• When button clicked, button notifies listenerslistener.actionPerformed(event);

• Listener sets text of text fieldtextField.setText("Hello, World!");

Page 31: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Outline

• Interface• Polymorphism• Function object• Anonymous class• User Interface Action

• Scope of variables• (Large) example• Graphics in Java

Page 32: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Accessing Variables from Enclosing Scope

• Remarkable: Inner class can access variables from enclosing scopee.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

Page 33: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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

bc

Which of the 3 ”final” can be removed without errors?

Page 34: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Outline

• Interface• Polymorphism• Function object• Anonymous class• User Interface Action• Scope of variables

• (Large) example• Graphics in Java

Page 35: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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

Page 36: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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

Page 37: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Implementing the Animation

Page 38: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Outline

• Interface• Polymorphism• Function object• Anonymous class• User Interface Action• Scope of variables• (Large) example

• Graphics in Java

Page 39: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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 interfaceShape s = . . .;g2.draw(s);

Page 40: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Drawing Rectangles

• Rectangle2D.Double constructed with  – top left corner – width – height

g2.draw(

new Rectangle2D.Double(x, y, width, height)

);

Page 41: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Drawing Ellipses

• For Ellipse2D.Double, specify bounding box

Page 42: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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);

Page 43: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Relationship Between Shape Classes

Page 44: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Drawing Text

• g2.drawString("Message", x, y); • x, y are base point coordinates

Page 45: Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

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)