What is a Method and how to create a Method in Apex?
A Method is a collection of statements that are grouped together to perform an operation.
void
doNothing() {}
void
doNothingWithArgs(String a, Integer b, Date c) {}
void
returnsNothing() { Integer i = 1; }
Integer
returnsInteger() { return 2009; }
Creating
a Method:
In
general, a method has the following syntax:
modifier
returnValueType methodName(list of parameters) {
// Method body;
}
A
method definition consists of a method header and a method body. Here are all
the parts of a method:
Modifiers: The modifier, which is optional,
tells the compiler how to call the method. This defines the access type of the
method.
Return Type: A method may return a value. The
returnValueType is the data type of the value the method returns. Some methods
perform the desired operations without returning a value. In this case, the
returnValueType is the keyword void.
Method Name: This is the actual name of the
method. The method name and the parameter list together constitute the method
signature.
Parameters: A parameter is like a placeholder.
When a method is invoked, you pass a value to the parameter. This value is
referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a method. Parameters are optional;
that is, a method may contain no parameters.
Method
Body: The method body contains a collection of statements that define what the
method does.
Ex:-
public static integer max(integer num1, integer num2) {
integer
result;
if
(num1 > num2)
result = num1;
else
result = num2;
return
result;
}
0 comments:
Post a Comment