


sum = sum + obj.getMeasure();public interface Measurable
{
double getMeasure();
}
public static double average(Measurable[] objects) { double sum = 0; for (Measurable obj : objects) { sum = sum + obj.getMeasure(); } if (objects.length > 0) { return sum / objects.length; } else { return 0; } }
This stand-mixer provides the “rotation”
service to any attachment that
conforms to a common interface.
Similarly, the average method at the
end of this section works with any class
that implements a common interfacepublic class BankAccount implements Measurable { ... public double getMeasure() { return balance; } }
Measurable obj = new BankAccount(); // OK
public class Country implements Measurable
{
public double getMeasure()
{
return area;
}
. . .
}

Average balance: 4000 Expected: 4000 Average area: 239950 Expected: 239950
public interface Named
{
String getName();
}public class Country implements Measurable, Named
Measurable meas = new Measurable(); System.out.println(meas.getMeasure());
Measurable meas = new Country("Uruguay", 176220);
System.out.println(meas.getName());
BankAccount account = new BankAccount(1000); Measurable meas = account; // OK
Country uruguay = new Country("Uruguay", 176220);
Measurable meas = uruguay; // Also OK // Also OK
Measurable meas = new Rectangle(5, 10, 20, 30); // ERROR


public static Measurable larger(Measurable obj1, Measurable obj2)
{
if (obj1.getMeasure() > obj2.getMeasure())
{
return obj1;
}
else
{
return obj2;
}
}
Country uruguay = new Country("Uruguay", 176220);
Country thailand = new Country("Thailand", 513120);
Measurable max = larger(uruguay, thailand);
Country maxCountry = (Country) max; String name = maxCountry.getName();

Which code below will construct a Measurable object?
Measurable[] data = { new BankAccount(10000), new Country("Belgium", 30510) };
System.out.println(average(data));
public interface Comparable
{
int compareTo(Object otherObject);
}
a.compareTo(b)
public class BankAccount implements Comparable
{
. . .
public int compareTo(Object otherObject)
{
BankAccount other = (BankAccount) otherObject;
if (balance < other.balance) { return -1; }
if (balance > other.balance) { return 1; }
return 0;
}
. . .
}BankAccount other = (BankAccount) otherObject;
BankAccount[] accounts = new BankAccount[3];
accounts[0] = new BankAccount(10000);
accounts[1] = new BankAccount(0);
accounts[2] = new BankAccount(2000);
Arrays.sort(accounts);
public class Country implements Comparable
{
. . .
public int compareTo(Object otherObject)
{
Country other = (Country) otherObject;
if (area < other.area) { return -1; }
if (area > other.area) { return 1; }
return 0;
}
}public static Comparable max(Comparable a, Comparable b)
{
if (a.compareTo(b) > 0) { return a; }
else { return b; }
}BankAccount larger = (BankAccount) max(first, second); System.out.println(larger.getBalance());Note that the result must be cast from Comparable to BankAccount so that you can invoke the getBalance method.
public interface Measurer
{
double measure(Object anObject);
}
public static double average(Object[] objects, Measurer meas) { double sum = 0; for (Object obj : objects) { sum = sum + meas.measure(obj); } if (objects.length > 0) { return sum / objects.length; } else { return 0; } }
public class AreaMeasurer implements Measurer
{
public double measure(Object anObject)
{
Rectangle aRectangle = (Rectangle) anObject;
double area = aRectangle.getWidth() * aRectangle.getHeight();
return area;
}
}
Rectangle aRectangle = (Rectangle) anObject;
Measurer areaMeas = new AreaMeasurer();
Rectangle[] rects
= { new Rectangle(5, 10, 20, 30), new Rectangle(10, 20, 30, 40) };
double averageArea = average(rects, areaMeas);

Average area: 625 Expected: 625
itself, that is, the implicit parameter.
public static Object max(Object a, Object b, Measurer m)
{
if (m.getMeasure(a) > m.getMeasure(b))
{
return a;
}
else { return b; }
}Rectangle larger = (Rectangle) max(first, second, areaMeas); System.out.println(larger.getWidth() + " by " + larger.getHeight());
public class MeasurerTester
{
public static void main(String[] args)
{
class AreaMeasurer implements Measurer
{
. . .
}
. . .
Measurer areaMeas = new AreaMeasurer();
double averageArea = Data.average(rects, areaMeas);
. . .
}
}
public class MeasurerTester
{
class AreaMeasurer implements Measurer
{
. . .
}
public static void main(String[] args)
{
Measurer areaMeas = new AreaMeasurer();
double averageArea = Data.average(rects, areaMeas);
. . .
}
}
MeasurerTester$1AreaMeasurer.class.
public void addScore(int studentId, double score) public double getAverageScore(int studentId) public void save(String filename)
public interface IGradeBook
{
void addScore(int studentId, double score);
double getAverageScore(int studentId);
void save(String filename);
. . .
}
public class MockGradeBook implements IGradeBook
{
private ArrayList<Double> scores;
public MockGradeBook() { scores = new ArrayList<Double>(); }
public void addScore(int studentId, double score)
{
// Ignore studentId
scores.add(score);
}
public double getAverageScore(int studentId)
{
double total = 0;
for (double x : scores) { total = total + x; }
return total / scores.size();
}
public void save(String filename)
{
// Do nothing
}
. . .
}
public interface ActionListener
{
void actionPerformed(ActionEvent event);
}
ActionListener listener = new ClickListener(); button.addActionListener(listener);
listener.actionPerformed(event);And the message is printed.

Whenever a button is pressed, the actionPerformed method is called on all listeners.
Specify button click actions through classes that implement the ActionListener interface.
JButton button = new JButton(". . .");
// This inner class is declared in the same method as the button variable
class MyListener implements ActionListener
{
. . .
}
ActionListener listener = new MyListener();
button.addActionListener(listener);
JButton button = new JButton("Add Interest");
final BankAccount account = new BankAccount(INITIAL_BALANCE);
// This inner class is declared in the same method as the account and button variables.
class AddInterestListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// The listener method accesses the account variable
// from the surrounding block
double interest = account.getBalance() * INTEREST_RATE / 100;
account.deposit(interest);
}
};
ActionListener listener = new AddInterestListener();
button.addActionListener(listener);
balance: 1100.0 balance: 1210.0 balance: 1331.0 balance: 1464.1

JButton button = new JButton("Add Interest");
JLabel label = new JLabel("balance: " + account.getBalance());
JPanel panel = new JPanel(); panel.add(button); panel.add(label); frame.add(panel);
class AddInterestListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
double interest = account.getBalance() * INTEREST_RATE / 100;
account.deposit(interest);
label.setText("balance=" + account.getBalance());
}
}
class MyListener implements ActionListener
{
void actionPerformed(ActionEvent event)
{
Listener action (executed at each timer event)
}
}
MyListener listener = new MyListener(); Timer t = new Timer(interval, listener); t.start();
Displays a rectangle that moves
The repaint method causes a component to repaint itself. Call this method whenever you modify the shapes that the paintComponent method draws
public interface MouseListener
{
void mousePressed(MouseEvent event);
// Called when a mouse button has been pressed on a component
void mouseReleased(MouseEvent event);
// Called when a mouse button has been released on a component
void mouseClicked(MouseEvent event);
// Called when the mouse has been clicked on a component
void mouseEntered(MouseEvent event);
// Called when the mouse enters a component
void mouseExited(MouseEvent event);
// Called when the mouse exits a component
}
public class MyMouseListener implements MouseListener
{
// Implements five methods
}
MouseListener listener = new MyMouseListener();
component.addMouseListener(listener);
First add a moveRectangle method to RectangleComponent
class MousePressListener implements MouseListener
{
public void mousePressed(MouseEvent event)
{
int x = event.getX();
int y = event.getY();
component.moveTo(x, y);
}
// Do-nothing methods
public void mouseReleased(MouseEvent event) {}
public void mouseClicked(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
}
