6 Object-oriented Programming

6.1

// Filename: Exercise1.java
interface Function {
    public int evaluate(int arg);
}

class Half implements Function {
    public int evaluate(int arg) {
        return arg/2;
    }
}

public class Exercise1 {
    public static int[] applyFunctionToArray(int[] arrIn) {
        int length = arrIn.length;
        int[] arrOut = new int[length];

        Function func = new Half();

        for (int i=0; i< length; i++)
            arrOut[i] = func.evaluate(arrIn[i]);

        return arrOut;
    }
}

6.2

// Filename: Exercise2.java
interface Function {
    public int evaluate(int arg);
}

class Half implements Function {
    public int evaluate(int arg) {
        return arg/2;
    }
}

class Print implements Function {
    public int evaluate(int arg) {
        System.out.println(arg);
        return arg;
    }
}

public class Exercise2 {
    public static void main(String[] args) {
        // Create array with values 1 .. 10
        int[] myArr = new int[10];
        for (int i=0; i<10;) myArr[i] = ++i;

        // Create a print function
        Function print = new Print();

        // Print array
        applyFunctionToArray(myArr, print);

        // Half values
        myArr = applyFunctionToArray(myArr, new Half());

        // Print array again
        applyFunctionToArray(myArr, print);
    }

    public static int[] applyFunctionToArray(int[] arrIn, Function func) {
        int length = arrIn.length;
        int[] arrOut = new int[length];

        for (int i=0; i< length; i++)
            arrOut[i] = func.evaluate(arrIn[i]);

        return arrOut;
    }
}

1
2
3
4
5
6
7
8
9
10
0
1
1
2
2
3
3
4
4
5

Output from the program: