<access_modifier> <return_type> <name>(<parameter_data_type> <parameter_name>, . . .) {
<body>
}
A method in Java describes a series of steps to be performed with data. A method has two main components:
- header
- body
Let’s see them in action.
public int addTwoNumbers(int number1, int number2) {
return number1 + number2;
}
The header is the first line, beginning with public
. This line defines the constraints of the method: its access modifier, return type, name, and its parameters, in that order. Let’s first discuss access modifiers.
Access Modifier
An access modifier defines the scope in which a method may be invoked (called), or modifies its implementation in the case of abstract
. The most commonly used modifiers are:
public
: allows access in all scopesprivate
: limits access to the current class’s scopeprotected
: limits access to the current class and all subclass’s scopestatic
: allows access to the method without needing to instantiate an object of its classabstract
: allows defining a method header but without providing an implementation for the body