public interface Measurable
{
double getMeasure();
}
public class DataSet
{
private double sum;
private Measurable maximum;
private int count;
public void add(Measurable x)
{
sum = sum + x.getMeasure();
if (count == 0 || maximum.getMeasure() < x.getMeasure())
maximum = x;
count++;
}
public Measurable getMaximum()
{
return maximum;
}
}
public class BankAccount implements Measurable
{
private double balance;
public BankAccount(double balance)
{
 this.balance = balance;
}
public double getMeasure()
{
 return balance;
}
}
public class Coin implements Measurable
{
private double value;
private String name;
public Coin(double value, String name)
{
 this.value = value;
 this.name = name;
}
public String toString()
{
 return "value: " + value + " name: " + name;
}
public double getMeasure()
{
 return value;
}
}
import java.awt.Rectangle;
public class DataSetTester
{
public static void main(String[] args)
{
DataSet bankData = new DataSet();
bankData.add(new BankAccount(100));
BankAccount account = new BankAccount(1000);
// the line below is OK
// you can assign an object that implements an interface
// to a variable of that interface type
Measurable y = account;
// The following line is not OK because the Rectangle
// class does not implement the Measurable interface:
// Measurable x = new Rectangle(5, 10, 15, 20);
DataSet coinData = new DataSet();
coinData.add(new Coin(0.25, "quarter"));
Coin coin = new Coin(0.10, "dime");
Measurable z = coin;
DataSet coinData2 = new DataSet();
coinData2.add(new Coin(0.25, "quarter"));
coinData2.add(new Coin(0.1, "dime"));
coinData2.add(new Coin(0.05, "nickel"));
Measurable max = coinData2.getMaximum();
// The line below will cause max.toString() to run:
System.out.println("max coin: " + max);
// You can convert from an interface type
// (Measurable) back to the original class.
Coin maxCoin = (Coin) max;
System.out.println("max coin: " + maxCoin);
// Demonstrate polymorphism (section 9.3):
System.out.println("\n\nDemonstrate polymorphism: ");
Measurable ba = new BankAccount(1000);
System.out.println(ba.getMeasure());
ba = new Coin(0.5, "half dollar");
System.out.println(ba.getMeasure());
// If you use an interface type like Measurable,
// you can only use the methods listed in the
// interface.
Measurable f = new BankAccount(100);
f.newMethod(); // CAUSES AN ERROR
BankAccount g = new BankAccount(100);
g.newMethod(); // works fine
System.out.println("DataSetTester ran.");
}
}