The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home Iteration Encapsulation and Generalization | ||
See also: Encapsulation | ||
Search the VIAS Library | Index | ||
Encapsulation and Generalization
Encapsulation usually means taking a piece of code and wrapping it up in a method, allowing you to take advantage of all the things methods are good for. We have seen two examples of encapsulation, when we wrote printParity in Section 4.3 and isSingleDigit in Section 5.7. Generalization means taking something specific, like printing multiples of 2, and making it more general, like printing the multiples of any integer. Here's a method that encapsulates the loop from the previous section and generalizes it to print multiples of n. public static void printMultiples (int n) {int i = 1; while (i <= 6) { System.out.print (n*i + " "); i = i + 1; } System.out.println (""); } To encapsulate, all I had to do was add the first line, which declares the name, parameter, and return type. To generalize, all I had to do was replace the value 2 with the parameter n. If I invoke this method with the argument 2, I get the same output as before. With argument 3, the output is: 3 6 9 12 15 18and with argument 4, the output is 4 8 12 16 20 24By now you can probably guess how we are going to print a multiplication table: we'll invoke printMultiples repeatedly with different arguments. In fact, we are going to use another loop to iterate through the rows. int i = 1;while (i <= 6) { printMultiples (i); i = i + 1; } First of all, notice how similar this loop is to the one inside printMultiples. All I did was replace the print statement with a method invocation. The output of this program is 1 2 3 4 5 62 4 6 8 10 12 3 6 9 12 15 18 4 8 12 16 20 24 5 10 15 20 25 30 6 12 18 24 30 36 which is a (slightly sloppy) multiplication table. If the sloppiness bothers you, Java provides methods that give you more control over the format of the output, but I'm not going to get into that here.
|
||
Home Iteration Encapsulation and Generalization |