Developing User Defined Methods
Introduction.
We have now written several different programs making use of Java's built
in packages, classes and methods. The next step is to develop our
own user defined methods. This
webpage will focus on the specifics of developing appropriate syntax for
declaring and defining these methods. Subsequent pages will present
more specific examples. I expect that you will go over this page and then refer back to it as we work examples. It will make little sense the first time through. But it should make more sense every time you encounter another method. Why develop your own methods?
Methods can be declared using the following general syntax.
While this probably makes less sense to you after having seen it we will discuss each of these. We will start with those that are most familiar. Return Types. In general methods can be considered to be of two main returnTypes
Parameter List. A parameter list is a list of variables and/or objects that come from outside the method to be used within the method. The developer needs to specify both the object and/or data type and give it a name or identifier. Thus a parameter list looks like the following. dataType identifier1, dataType identifier2, objectType identifier3 ... where they can be listed in any order desired as long as each identifier is paired with its appropriate type. Method Names. Methods can be named just like any variables. It is relatively standard practice to start with a lower case letter just like for variables.
Modifiers. Without saying very much about their meaning until we use them, some typical modifiers are
Some Examples. Now we present some examples. We've already seen several of these.
Method Invocation. The way to cause a method to execute depends on whether it returns a value.
Returning a Result. When you want to return something back to where it was called you need to have declared an object or variable of the appropriate type earlier in the program.
Or it might be an expression that evaluates to the appropriate genericType. Then within the method you need a statement at the appropriate location when you want to be done with the method and return the value.
or
Now we will start working examples in subsequent webpages. |