|
With the variable declarations, we have seen how the ‘state’ of an object can be implemented in a Java class. Now let us see how you can implement object’s ‘behavior’ through method declarations. You can define a method within a class or an interface body. You can specify the method’s return type, its name, arguments in its declaration. The general format for a method declaration in class body is:
[modifiers] returntype methodName([argumentList]) {
[method body]
}
The elements between the pair of square brackets [] are optional. The modifiers is a list of method modifiers that declares various attributes of method such as whether the other classes can have access to it. We will discuss method modifiers in chapter 3. The returnType is the data type of a value that the method may return. If a method doesn’t return any value then the returnType is specified as void. The argumentList is a comma-separated list of arguments passed to the method. You can also declare methods that take no argument or take only one argument. For example, in listing 1.1 the withdraw() method which takes just one argument as:
public void withdraw(float amount) {
balance = balance - amount;
}
Note that this method does not return any value. Therefore, its return type is void. The method body contains Java code to implement the bank account’s (withdraw) behavior.