Writing Methods
Writing Methods
Method Definition
- A method is a collection of statements that perform some operation.
- It is defined within a class and represents the behaviour of an object of that class.
Method Declaration Format
- The format typically is:
accessModifier returnType methodName(parameters) {
// body of the method
}
- The access modifier (such as
public
orprivate
) controls the access level of the method. - returnType is the data type that the method returns. If the method does not return a value, its returnType is
void
. - The methodName is the identifier that is used to call the method.
- parameters are the list of variables defined by their type and name that this method receives.
Invoking a Method
- A method is invoked (called) using the his method name and the parameters needed by the method.
Method Behaviour and Control Flow
- Statements inside a method are executed sequentially from top to bottom.
- A method can call other methods, create variables, and perform calculations, among other actions.
- Control structures like loops and conditional statements can be included in a method to guide its execution flow.
Parameters and Arguments
- Parameters are variables defined by the method during its declaration.
- Methods can be invoked with arguments, data values passed to the method during its call.
- The number and type of arguments supplied when calling a method must match the number and type of parameters defined by the method declaration.
Return Statement
- A
return
statement is used to conclude a method’s execution and potentially pass a value back to its calling statement. - The type of this returned value must match the returnType declared in the method header.
Importance of Methods
- Methods allow for code reuse, so similar operations only need to be written once.
- By clearly defining methods with precise behaviours, one can construct complex applications using a modular and organised approach.
- Proper use of methods promotes the OOP principle of Encapsulation, ensuring data is safely accessed and modified.