SE450: Horstmann Chapter 4

Contents [0/41]

Object-Oriented Design & Patterns [1/41]
Chapter Topics [2/41]
Displaying an Image [3/41]
Displaying an Image [4/41]
Displaying an Image [5/41]
The Icon Interface Type [6/41]
Interface Types [7/41]
The Icon Interface Type and Implementing Classes [8/41]
Polymorphism [9/41]
Polymorphism [10/41]
A Variable of Interface Type [11/41]
Polymorphism [12/41]
Benefits of Polymorphism [13/41]
The Comparable Interface Type [14/41]
The Comparable Interface Type [15/41]
The Comparator interface type [16/41]
The Comparator interface type [17/41]
Anonymous Classes [18/41]
Anonymous Classes [19/41]
Anonymous Classes [20/41]
Frames [21/41]
Adding Components [22/41]
User Interface Actions [23/41]
User Interface Actions [24/41]
Accessing Variables from Enclosing Scope [25/41]
User Interface Actions [26/41]
Constructing Related Actions [27/41]
Timers [28/41]
Drawing Shapes [29/41]
Drawing Rectangles and Ellipses [30/41]
Drawing Ellipses [31/41]
Drawing Line Segments [32/41]
Relationship Between Shape Classes [33/41]
Drawing Text [34/41]
Filling Shapes [35/41]
Defining a New Interface Type [36/41]
CRC Card for the MoveableShape Interface Type [37/41]
Defining a New Interface Type [38/41]
Implementing the Animation [39/41]
Implementing the Animation [40/41]
Implementing the Animation [41/41]

Object-Oriented Design & Patterns [1/41]

Cay S. Horstmann

Chapter 4

Interfaces and Polymorphism

horstmann-oodp2

Chapter Topics [2/41]

Displaying an Image [3/41]

.

Displaying an Image [4/41]

.

Displaying an Image [5/41]

.

The Icon Interface Type [6/41]

public interface Icon
{
int getIconWidth();
int getIconHeight();
void paintIcon(Component c, Graphics g, int x, int y)
}

Interface Types [7/41]

file:horstmann/ch04_icon2/MarsIcon.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package horstmann.ch04_icon2;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;

import javax.swing.Icon;

/**
   An icon that has the shape of the planet Mars.
 */
public class MarsIcon implements Icon
{
  /**
      Constructs a Mars icon of a given size.
      @param aSize the size of the icon
   */
  public MarsIcon(int aSize)
  {
    size = aSize;
  }

  public int getIconWidth()
  {
    return size;
  }

  public int getIconHeight()
  {
    return size;
  }

  public void paintIcon(Component c, Graphics g, int x, int y)
  {
    Graphics2D g2 = (Graphics2D) g;
    Ellipse2D.Double planet = new Ellipse2D.Double(x, y,
        size, size);
    g2.setColor(Color.RED);
    g2.fill(planet);
  }

  private int size;
}

file:horstmann/ch04_icon2/IconTester.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
package horstmann.ch04_icon2;
import javax.swing.JOptionPane;

public class IconTester
{
  public static void main(String[] args)
  {
    JOptionPane.showMessageDialog(
        null,
        "Hello, Mars!",
        "Message",
        JOptionPane.INFORMATION_MESSAGE,
        new MarsIcon(50));
    System.exit(0);
  }
}

The Icon Interface Type and Implementing Classes [8/41]

.

Polymorphism [9/41]

Polymorphism [10/41]

A Variable of Interface Type [11/41]

.

Polymorphism [12/41]

Benefits of Polymorphism [13/41]

The Comparable Interface Type [14/41]

The Comparable Interface Type [15/41]

file:horstmann/ch04_sort1/Country.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package horstmann.ch04_sort1;
/**
   A country with a name and area.
 */
public class Country implements Comparable<Country>
{
  /**
      Constructs a country.
      @param aName the name of the country
      @param anArea the area of the country
   */
  public Country(String aName, double anArea)
  {
    name = aName;
    area = anArea;
  }

  /**
      Gets the name of the country.
      @return the name
   */
  public String getName()
  {
    return name;
  }

  /**
      Gets the area of the country.
      @return the area
   */
  public double getArea()
  {
    return area;
  }


  /**
      Compares two countries by area.
      @param other the other country
      @return a negative number if this country has a smaller
      area than otherCountry, 0 if the areas are the same,
      a positive number otherwise
   */
  public int compareTo(Country other)
  {
    if (area < other.area) return -1;
    if (area > other.area) return 1;
    return 0;
  }

  private String name;
  private double area;
}

file:horstmann/ch04_sort1/CountrySortTester.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
package horstmann.ch04_sort1;
import java.util.ArrayList;
import java.util.Collections;

public class CountrySortTester
{
  public static void main(String[] args)
  {
    ArrayList<Country> countries = new ArrayList<Country>();
    countries.add(new Country("Uruguay", 176220));
    countries.add(new Country("Thailand", 514000));
    countries.add(new Country("Belgium", 30510));

    Collections.sort(countries);
    // Now the array list is sorted by area
    for (Country c : countries)
      System.out.println(c.getName() + " " + c.getArea());
  }
}

The Comparator interface type [16/41]

The Comparator interface type [17/41]

file:horstmann/ch04_sort2/CountryComparatorByName.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
package horstmann.ch04_sort2;
import java.util.Comparator;

public class CountryComparatorByName implements Comparator<Country>
{
  public int compare(Country country1, Country country2)
  {
    return country1.getName().compareTo(country2.getName());
  }

}

file:horstmann/ch04_sort2/ComparatorTester.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
package horstmann.ch04_sort2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ComparatorTester
{
  public static void main(String[] args)
  {
    ArrayList<Country> countries = new ArrayList<Country>();
    countries.add(new Country("Uruguay", 176220));
    countries.add(new Country("Thailand", 514000));
    countries.add(new Country("Belgium", 30510));
    Comparator<Country>  comp = new CountryComparatorByName();
    Collections.sort(countries, comp);
    // Now the array list is sorted by area
    for (Country c : countries)
      System.out.println(c.getName() + " " + c.getArea());
  }
}

Anonymous Classes [18/41]

Anonymous Classes [19/41]

Anonymous Classes [20/41]

Frames [21/41]

Adding Components [22/41]

.

file:horstmann/ch04_frame/FrameTester.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package horstmann.ch04_frame;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class FrameTester
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame();

    JButton helloButton = new JButton("Say Hello");
    JButton goodbyeButton = new JButton("Say Goodbye");

    final int FIELD_WIDTH = 20;
    JTextField textField = new JTextField(FIELD_WIDTH);
    textField.setText("Click a button!");

    frame.setLayout(new FlowLayout());

    frame.add(helloButton);
    frame.add(goodbyeButton);
    frame.add(textField);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}

User Interface Actions [23/41]

User Interface Actions [24/41]

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

Accessing Variables from Enclosing Scope [25/41]

User Interface Actions [26/41]

file:horstmann/ch04_action1/ActionTester.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package horstmann.ch04_action1;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class ActionTester
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame();

    final int FIELD_WIDTH = 20;
    final JTextField textField = new JTextField(FIELD_WIDTH);
    textField.setText("Click a button!");

    JButton helloButton = new JButton("Say Hello");

    helloButton.addActionListener(event -> textField.setText("Hello, World!"));

    JButton goodbyeButton = new JButton("Say Goodbye");

    goodbyeButton.addActionListener(event -> textField.setText("Goodbye, World!"));

    frame.setLayout(new FlowLayout());

    frame.add(helloButton);
    frame.add(goodbyeButton);
    frame.add(textField);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}

Constructing Related Actions [27/41]

public static ActionListener createGreetingButtonListener(
final String message)
{
return new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
textField.setText(message);
}
};
}

Timers [28/41]

.

file:horstmann/ch04_timer/TimerTester.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package horstmann.ch04_timer;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.Timer;

/**
   This program shows a clock that is updated once per second.
 */
public class TimerTester
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame();

    final int FIELD_WIDTH = 20;
    final JTextField textField = new JTextField(FIELD_WIDTH);

    frame.setLayout(new FlowLayout());
    frame.add(textField);

    ActionListener listener = event -> {
      Date now = new Date();
      textField.setText(now.toString());
    };
    final int DELAY = 1000;
    // Milliseconds between timer ticks
    Timer t = new Timer(DELAY, listener);
    t.start();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}

Drawing Shapes [29/41]

Drawing Rectangles and Ellipses [30/41]

Drawing Ellipses [31/41]

.

Drawing Line Segments [32/41]

Relationship Between Shape Classes [33/41]

.

Drawing Text [34/41]

.

Filling Shapes [35/41]

.

file:horstmann/ch04_icon3/CarIcon.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

package horstmann.ch04_icon3;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

import javax.swing.Icon;

/**
   An icon that has the shape of a car.
 */
public class CarIcon implements Icon
{
  /**
      Constructs a car of a given width.
      @param aWidth the width of the car
   */
  public CarIcon(int aWidth)
  {
    width = aWidth;
  }

  public int getIconWidth()
  {
    return width;
  }

  public int getIconHeight()
  {
    return width / 2;
  }

  public void paintIcon(Component c, Graphics g, int x, int y)
  {
    Graphics2D g2 = (Graphics2D) g;
    Rectangle2D.Double body
    = new Rectangle2D.Double(x, y + width / 6,
        width - 1, width / 6);
    Ellipse2D.Double frontTire
    = new Ellipse2D.Double(x + width / 6, y + width / 3,
        width / 6, width / 6);
    Ellipse2D.Double rearTire
    = new Ellipse2D.Double(x + width * 2 / 3, y + width / 3,
        width / 6, width / 6);

    // The bottom of the front windshield
    Point2D.Double r1
    = new Point2D.Double(x + width / 6, y + width / 6);
    // The front of the roof
    Point2D.Double r2
    = new Point2D.Double(x + width / 3, y);
    // The rear of the roof
    Point2D.Double r3
    = new Point2D.Double(x + width * 2 / 3, y);
    // The bottom of the rear windshield
    Point2D.Double r4
    = new Point2D.Double(x + width * 5 / 6, y + width / 6);

    Line2D.Double frontWindshield
    = new Line2D.Double(r1, r2);
    Line2D.Double roofTop
    = new Line2D.Double(r2, r3);
    Line2D.Double rearWindshield
    = new Line2D.Double(r3, r4);

    g2.fill(frontTire);
    g2.fill(rearTire);
    g2.setColor(Color.red);
    g2.fill(body);
    g2.draw(frontWindshield);
    g2.draw(roofTop);
    g2.draw(rearWindshield);
  }

  private int width;
}


Defining a New Interface Type [36/41]

.

CRC Card for the MoveableShape Interface Type [37/41]

.

Defining a New Interface Type [38/41]

Implementing the Animation [39/41]

Implementing the Animation [40/41]

file:horstmann/ch04_animation/MoveableShape.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
package horstmann.ch04_animation;
import java.awt.Graphics2D;

/**
   A shape that can be moved around.
 */
public interface MoveableShape
{
  /**
      Draws the shape.
      @param g2 the graphics context
   */
  void draw(Graphics2D g2);
  /**
      Moves the shape by a given amount.
      @param dx the amount to translate in x-direction
      @param dy the amount to translate in y-direction
   */
  void translate(int dx, int dy);
}

file:horstmann/ch04_animation/ShapeIcon.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package horstmann.ch04_animation;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.Icon;

/**
   An icon that contains a moveable shape.
 */
public class ShapeIcon implements Icon
{
  public ShapeIcon(MoveableShape shape,
      int width, int height)
  {
    this.shape = shape;
    this.width = width;
    this.height = height;
  }

  public int getIconWidth()
  {
    return width;
  }

  public int getIconHeight()
  {
    return height;
  }

  public void paintIcon(Component c, Graphics g, int x, int y)
  {
    Graphics2D g2 = (Graphics2D) g;
    shape.draw(g2);
  }

  private int width;
  private int height;
  private MoveableShape shape;
}


file:horstmann/ch04_animation/AnimationTester.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package horstmann.ch04_animation;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

/**
   This program implements an animation that moves
   a car shape.
 */
public class AnimationTester
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame();

    final MoveableShape shape
    = new CarShape(0, 0, CAR_WIDTH);

    ShapeIcon icon = new ShapeIcon(shape,
        ICON_WIDTH, ICON_HEIGHT);

    final JLabel label = new JLabel(icon);
    frame.setLayout(new FlowLayout());
    frame.add(label);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

    final int DELAY = 100;
    // Milliseconds between timer ticks
    Timer t = new Timer(DELAY, event -> {
      shape.translate(1, 0);
      label.repaint();
    });
    t.start();
  }

  private static final int ICON_WIDTH = 400;
  private static final int ICON_HEIGHT = 100;
  private static final int CAR_WIDTH = 100;
}

file:horstmann/ch04_animation/CarShape.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package horstmann.ch04_animation;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

/**
   A car that can be moved around.
 */
public class CarShape implements MoveableShape
{
  /**
      Constructs a car item.
      @param x the left of the bounding rectangle
      @param y the top of the bounding rectangle
      @param width the width of the bounding rectangle
   */
  public CarShape(int x, int y, int width)
  {
    this.x = x;
    this.y = y;
    this.width = width;
  }

  public void translate(int dx, int dy)
  {
    x += dx;
    y += dy;
  }

  public void draw(Graphics2D g2)
  {
    Rectangle2D.Double body
    = new Rectangle2D.Double(x, y + width / 6,
        width - 1, width / 6);
    Ellipse2D.Double frontTire
    = new Ellipse2D.Double(x + width / 6, y + width / 3,
        width / 6, width / 6);
    Ellipse2D.Double rearTire
    = new Ellipse2D.Double(x + width * 2 / 3, y + width / 3,
        width / 6, width / 6);

    // The bottom of the front windshield
    Point2D.Double r1
    = new Point2D.Double(x + width / 6, y + width / 6);
    // The front of the roof
    Point2D.Double r2
    = new Point2D.Double(x + width / 3, y);
    // The rear of the roof
    Point2D.Double r3
    = new Point2D.Double(x + width * 2 / 3, y);
    // The bottom of the rear windshield
    Point2D.Double r4
    = new Point2D.Double(x + width * 5 / 6, y + width / 6);
    Line2D.Double frontWindshield
    = new Line2D.Double(r1, r2);
    Line2D.Double roofTop
    = new Line2D.Double(r2, r3);
    Line2D.Double rearWindshield
    = new Line2D.Double(r3, r4);

    g2.draw(body);
    g2.draw(frontTire);
    g2.draw(rearTire);
    g2.draw(frontWindshield);
    g2.draw(roofTop);
    g2.draw(rearWindshield);
  }

  private int x;
  private int y;
  private int width;
}

Implementing the Animation [41/41]

.

Revised: 2007/09/11 16:22