/*
 * Series.java by Richard J. Davies
 * from `Introductory Java for Scientists and Engineers'
 * chapter: `Object Orientation'
 * section: `Example - Methods as Arguments'
 *
 * This program sums the first 10 terms of a series. The interesting feature
 * is that the series is defined by a function, and we pass the function
 * as an argument to the routine which computes the sum. This is achieved
 * using interfaces. You would use a similar mechanism to write methods such as
 * an integration method which was passed the function to integrate. In
 * addition, you should note that we define more than one class in a single
 * .java file. This is allowed  since only one of the classes is declared as
 * public.
 */

// An interface for objects capable of generating
// the elements of a series from their indices.
interface Generator
{
  double element(int n);
}


// An example of a class that implements this
// interface to generate a series of squares.
class SquareGenerator implements Generator
{
   public double element(int n)
  {
    return n*n;
  }
}


// The public class in the file.
public class Series
{
  // This function takes any object capable of
  // generating a series and sums the terms from
  // zero up to `number'.
  public static double sum(Generator g, int number)
  {
    double ans = 0;

    for (int i=0; i<=number; i++)
      ans += g.element(i);

    return ans;
  }

  // The main method creates one of our square
  // series generators and uses the generic series
  // summing method to add the first 10 elements.
  public static void main(String[] argv)
  {
    SquareGenerator s = new SquareGenerator();

    double x = sum(s, 10);

    System.out.println("Sum of elements 0 to 10 is: " + x);
  }
}

