![]() ![]() ![]() ![]() |
Objects, Classes, and Interfaces |
As you know, objects have behaviour and that behaviour is implemented by its methods. Other objects can ask an object to do something by invoking its methods. This section tells you everything you need to know to write methods for your Java classes. For more information about how to call methods see Using an Object.In Java, you define a class's methods within the body of the class for which the method implements some behaviour. Typically, you declare a class's methods after its variables in the class body although this is not required.
Similar to a class implementation, a method implementation consists of two parts: the method declaration and the method body.
methodDeclaration { . . . methodBody . . . }The Method Declaration
At minimum, the method declaration component of a method implementation has a return type indicating the data type of the value returned by the method, and a name.For example, the following declares of a simple method namedreturnType methodName() { . . . }isEmpty()
within the Stack class that returns a boolean value (true or false).The method declaration shown above is very basic. Methods have many other attributes such as arguments, access control, and so on. This section will cover these topics as well as expand upon the features illustrated in the method declarations above.class Stack { . . . boolean isEmpty() { . . . } }The Method Body
The method body is where all of the action of a method takes place; the method body contains all of the legal Java instructions that implement the method. For example, here is the Stack class with an implementation for theisEmpty()
method.Within the method body, you can useclass Stack { static final int STACK_EMPTY = -1; Object stackelements[]; int topelement = STACK_EMPTY; . . . boolean isEmpty() { if (topelement == STACK_EMPTY) return true; else return false; } }this
to refer to the current object. Thethis
keyword and other method body features are covered in this section.
![]() ![]() ![]() ![]() |
Objects, Classes, and Interfaces |