Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Section 7. Object-Oriented Programming

7. Object-Oriented Programming

7.1
//Filename: Exercise1.java
package chap07_PE1;

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

  public static void main(String[] args) {
    // Create array with values 1..10
    int length = 10;
    int[] myArr = new int[length];
    for (int i = 0; i < length;) myArr[i] = ++i;
    // Print array
    for (int value : myArr) System.out.println(value);
    // Half values
    myArr = applyFunctionToArray(myArr);
    // Print array again
    for (int value : myArr) System.out.println(value);
  }
}

					  

7.2
package chap07_PE2;

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

  public static void main(String[] args) {
    // Create array with values 1..10
    int length = 10;
    int[] myArr = new int[length];
    for (int i = 0; i < length;) 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);
  }
}

					  


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint