In this unit you will learn: -
about the importance of methods for reusing
code -
how to define an object method -
about how arguments relate to parameters -
how static methods differ from object methods By now, we have seen several instances of
method invocations, but it may not be completely clear what a method actually
is. To put a definition to what we’ve
been using, a method is simply a set of code statements to accomplish a
specific task. As Java programs grow
larger, methods allow us to break down a problem into smaller tasks. The basis for this is the notion of abstraction, a widely used problem solving
technique that we can illustrate with an example. Suppose we’re interested in writing a
program that draws a geometric representation of a honeycomb. To simplify our task, we can think of the
honeycomb as a collection of hexagons (placed appropriately of course). Before we can think of drawing the full
honeycomb, it would be really helpful if we know how to draw a hexagon. Knowing the angle between the sides and how
to draw lines is essentially all we need to write some code that draws a
hexagon. Since we’re going to need to
draw many hexagons for the honeycomb, it would be great if we could package
all the code needed to draw the hexagon and not have to type the code for
every hexagon we want to draw – that’s exactly what the method does for
us. To draw a hexagon, we would just
invoke the method using its name.
Having already abstracted the drawing of a hexagon into a method, we
could focus on the placement of hexagons to form the honeycomb without
worrying about the delays of drawing individual hexagons. By repeatedly invoking a method we’re in
effect reusing the code that it executes.
In Java, as in other object-oriented languages, there are two types of
methods that we’ll encounter: 1) object methods, which are invoked using an
object reference, and 2) class methods (or static methods), which are invoked
using a class name (for which an object needs not be created). |