Working with Methods


Home Up Search Java 2 API C++ Resources

Methods are the means in which an object communicates with other objects, including itself.  They are the behavior of an object and define what an object is to the rest of the program.   Private methods are used for communication within the object and are very useful for encapsulating code into abstract forms.

Inherent with a method is an operational "contract".   This contract specifies

  1. What the method does and the reason for its existence.
  2. What pre-conditions must be met before the method can be safely used.
  3. What post-conditions will be true after the method has been run.
  4. What each argument means.   That is, what information does each argument convey to the object.
  5. The meaning of the returned result.
  6. The type of the returned result of the executing the method.
  7. The type of each input argument and order in which the arguments a given.

The code for a method will only specify the last two of the above contract requirements!  The rest of the contract must be written in the documentation for the object.

Using Methods

Methods are called using the "dot notation":    [object name].[method name]([input values])

For instance:   

        myBall.getRadius()

        myBall.setRadius(42)

        aRectangle.setColor(aColor)

       aRectangle.setSides(23, 95)

Methods can return values that can be used as any other values.   That is, the call to the method of an object can be considered a substitute for the original value.

For instance:

      int x;

      x = myBall.getRadius();

      aSquare.setSide( myBall.getRadius());

     Color c = thePolygon.getColor();

Writing Methods

Concrete methods:

The syntax for declaring a method consists of a "signature" and a "body" encosed by {}:

[scoping] [return type] method_name ([Input Type] input_name, [AnotherType] another_name))
{
      [body of code goes here -- the code that actually does the job.]

Examples:

public void setSize(int size)
{
      this.size = size;
}

 

Abstract methods have no body because they represent the concept of a certain behavior, but not necessarily any particular way of executing that behavior.     They are used when the user deals with a behavior strictly in its abstract sense, that is, that the behavior exists and that it is not important exactly what is done, just that it is done.   The syntax is the same as any method signature but with the "abstract" keyword and a semicolon at the end:

abstract

abstract [scoping] [return type] method_name ([Input Type] input_name, [AnotherType] another_name));

Example:

abstract public Color getColor();