CS 46A - Lecture 24

Cover page image

Pre-class reading

Final Exam

Using Interfaces for Algorithm Reuse

Using Interfaces for Algorithm Reuse

Or suppose we wanted to find the coin with the highest value among a set of coins. We would need to modify the DataSet class again:

public class DataSet // Modified for Coin objects
{
   private double sum;
   private Coin maximum;
   private int count;
   . . .
   public void add(Coin x)
   {
      sum = sum + x.getValue();
      if (count == 0 || maximum.getValue() < x.getValue())
         maximum = x;
      count++;
   }

   public Coin getMaximum()
   {
      return maximum;
   }
}

Using Interfaces for Algorithm Reuse

Syntax 9.1 Declaring an Interface

Interfaces vs. Classes

An interface type is similar to a class, but there are several important differences:

DataSet for Measurable Objects

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

Implementing an Interface Type

Code Reuse

Syntax 9.2 Implementing an Interface

UML Diagram of DataSet and Related Classes

ch09/measure1/DataSetTester.java

Your browser does not support the <object> tag.

ch09/measure1/DataSetTester.java

Program Run:

Lecture 24 Clicker Question 1

Why can't the add method of the DataSet class have a parameter of type Object?

  1. Because Object is a class, not an interface
  2. Because Object does not have a getMeasure method
  3. Because BankAccount doesn't implement Object
  4. Because Object does not have a getBalance method

Lecture 24 Clicker Question 2

Suppose you want to use the DataSet class to find the Country object with the largest population. What condition must the Country class fulfill?

  1. It must implement the Object interface
  2. It must implement the Measurable interface
  3. It must provide a getMeasure method that returns the country's population
  4. Both 2 and 3

Converting Between Class and Interface Types

Variables of Class and Interface Types

Variables of Class and Interface Types

Casts

Lecture 24 Clicker Question 3

Given the code

BankAccount acct = new BankAccount();
Coin dime = new Coin("dime", 0.1);
Measurable meas = new Coin("quarter", 0.25);

which of the following statements are correct?

  1. acct = (BankAccount) meas;
  2. dime = (Coin) meas;
  3. acct = meas;
  4. dime = meas;

Polymorphism

Interface Reference

Interface Reference

Polymorphism