Breaking News

Implementing Methods

Methods

1. Are named modules of code

2. May optionally receive one or more parameters (arguments)

3. May optionally return a single value

4. Are associated with either a class or an object of a class. The former are called “class methods” and are the focus of this lesson. The latter are called “instance methods” and will be covered in a later lesson.

Calling a class method
• Involves the following general syntax for the call expression:
class-name.method-name(arguments)

If the method is defined within the current class, the class name may be omitted and the general syntax for the call expression is:
method-name(arguments)

• Can occur anywhere the returned data type makes sense. Methods that return no value are called in a stand-alone statement. Methods that return a value are called within another expression.

This method pushes an object, the one passed in as an argument, onto the top of the stack, and returns it.

Like a class, a method has two major parts:
1. method declaration
2. And method body.

The method declaration defines all of the method’s attributes, such as access level, return type, name, and arguments, as illustrated here:

The method body is where all the action takes place. It contains the Java instructions that implement the method.

The Method Declaration
At minimum, a method declaration has a name and a return type indicating the data type of the value returned by the method:

returnType methodName()
{
. . .
}

Check Also

Casts

1. Are a programmer’s way of telling the compiler to ignore possible loss of data …