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 Fruitful Methods Composition  
See also: Composition  
Search the VIAS Library  Index  
Composition
As you should expect by now, once you define a new method, you can use it as part of an expression, and you can build new methods using existing methods. For example, what if someone gave you two points, the center of the circle and a point on the perimeter, and asked for the area of the circle? Let's say the center point is stored in the variables xc and yc, and the perimeter point is in xp and yp. The first step is to find the radius of the circle, which is the distance between the two points. Fortunately, we have a method, distance that does that. double radius = distance (xc, yc, xp, yp);The second step is to find the area of a circle with that radius, and return it. double area = area (radius);return area; Wrapping that all up in a method, we get: public static double fred(double xc, double yc, double xp, double yp) { double radius = distance (xc, yc, xp, yp); double area = area (radius); return area; } The name of this method is fred, which may seem odd. I will explain why in the next section. The temporary variables radius and area are useful for development and debugging, but once the program is working we can make it more concise by composing the method invocations: public static double fred(double xc, double yc, double xp, double yp) { return area (distance (xc, yc, xp, yp)); }


Home Fruitful Methods Composition 