Method in Apex:
A method is a way to perform some operation. Similarly, the method in Apex is a collection of instructions that performs some task. It provides the reusability of code. In this section, we will learn what is a method in Apex, types of methods, method declaration, and how to call a method in Apex.
What is a method in Apex?
A method is a block of statements or a set of code grouped together to perform a specific operation. It is used to achieve the reusability of code because we write a method at once and use it many times whenever required. We can easily modify the code just by adding or removing code as per requirement. The method is executed only when we call or invoke as per need.
The method declaration provides information about method, such as what would be visibility, return-type, name, and its arguments as we are showing in the following figure.
Method Signature: Every method has its own method signature. It is a part of the method declaration. It includes the method name and argument/parameter list.
Access Specifier: Access specifier/modifier is the access type of the method. It specifies the visibility of the method which means from where we can call our method. Java provides four types of access specifier:
- global: The method is accessible by all classes within the Salesforce or outside the Salesforce when we use global specifier in our application.
- public: The method is accessible by all the classes within the Saleforce.
- Private: When we use a private access specifier, the method is only accessible within the class where we defined it.
- Protected: When we use protected access specifier in Apex class, the method is accessible to any inner classes in the defining Apex class, and to the classes that extend the defining Apex class as per need.
Return Type: Return type is a data type that the method is going to return. It may have a primitive data type, sObject, collection, void, etc. as per requirement, If the method does not return anything, we use void keyword. So void means that method is not going to return any value.
Method Name: It is a unique name that is used to define the name of a method. Please make sure the name which you are going to take for your method, must be corresponding to the functionality of the method. So that by reading the name of the method we can understand that what this method is going to perform.
Parameter/Argument List: It is the list of parameters/arguments separated by a comma. It’s having the data type and variable name. If the method has no parameter, left the parentheses as blank.
Method Body: In the method body we will define our business logic. It is enclosed within the pair of curly braces, that is nothing but defines method scope.