// ApplierInt.java // ApplierInt.java uses interfaces to apply an arbitrary function to an // in array // IntFun is an interface declaring f as a method from int to int. interface IntFun { public int f(int x); } // Incr instantiates method f to be the increment function class Incr implements IntFun { public int f(int i) { return i+1; } } // end Incr // Doub instantiates method f to be the doubling function class Doub implements IntFun { public int f(int i) { return 2*i; } } // end Doub public class ApplierInt { // ApplyToArray applies Q.f to the elements of A and puts the result in B. public static void ApplyToArray(IntFun Q, int[] A, int[] B) { for (int i = 0; i < A.length; i++) B[i] = Q.f(A[i]); } public static void main(String args[]) { int A[] = new int[] { 1,2,3 }; int B[] = new int[3]; Incr Inc = new Incr(); Doub Dub = new Doub(); ApplyToArray(Inc,A,B); System.out.println(B[0] + " " + B[1] + " " + B[2]); ApplyToArray(Dub,A,B); System.out.println(B[0] + " " + B[1] + " " + B[2]); } } // end ApplierInt