image image image image image
Text Size
(0 votes, average 0 out of 5)

Messages

Software objects interact and communicate with each other by sending messages to each other. When object A wants object B to perform one of B's methods, object A sends a message to object B as shown in the following figure (diagram from The Java Tutorial):

 

Messages

Sometimes, the receiving object needs more information so that it knows exactly what to do; This information is passed along with the message as parameters.

There are three parts of a message:

  1. The object to which the message is addressed
  2. The name of the method to perform
  3. Any parameters needed by the method

Methods

Methods are used to implement the functionality of a class. They can be

  • Public – can be accessed by any other class, sub-class, or object;
  • Protected – can only be accessed by other methods of the same class or sub-class;
  • Private – can only be accessed by other methods of the same class.

If none of the above is specified, then the method can only be accessed by other methods in the same class (or package).

A method definition has two major parts: the method declaration and the method body. The method declaration defines all the method's attributes, such as access level, return type, name, and arguments, as shown in the following figure. The method body is where all the action takes place. It contains the instructions that implement the method. See the example below (from The Java Tutorial):

push Method

The only required elements of a method declaration are the method's name, return type, and a pair of parentheses: '(' and ')'. A method declaration can provide more information about the method, including the return type of the method, the number and type of the arguments required by the method, and which other classes and objects can call the method. This is shown below (from The Java Tutorial):

Method details

Although a method name can be any legal identifier, code conventions restrict method names. In general, method names should be verbs and should be in mixed case, with the first letter in lowercase and the first letter of each internal word in uppercase. Here are some examples:

toString
compareTo
isDefined
setX
getX

A method name should not be the same as the class name, because constructors have the same name as the class name. In addition, a method has a unique name within its class. However, three situations might cause a method to have the same name as other methods in the class or in a superclass: overriding methods, hiding methods, and name overloading.

Add comment


Security code
Refresh