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

Chapter 7. Object-Oriented Programming > Programming Exercises

Programming Exercises

7.1Declare an interface called Function that has a method named evaluate that takes an int parameter and returns an int value.

Create a class called Half that implements the Function interface. The implementation of the method evaluate() should return the value obtained by dividing the int argument by 2.

In a client, create a method that takes an arbitrary array of int values as a parameter, and returns an array that has the same length, but the value of an element in the new array is half that of the value in the corresponding element in the array passed as the parameter. Let the implementation of this method create an instance of Half, and use this instance to calculate values for the array that is returned.

7.2Rewrite the method that operated on arrays from the previous exercise: the method should now also accept a Function reference as an argument, and use this argument instead of an instance of the Half class.

Create a class called Print that implements the method evaluate() in the Function interface. This method simply prints the int value passed as argument, and returns this value.

Now, write a program that creates an array of int values from 1 to 10, and does the following:

  • Prints the array using an instance of the Print class and the method described earlier.

  • Halves the values in the array and prints the values again, using the Half and Print classes, and the method described above.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

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

  

Start a Free Trial


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