Class Methods

To define a method, specify the following:
  • Optional: Modifiers, such as public or protected.
  • Required: The data type of the value returned by the method, such as String or Integer. Use void if the method does not return a value.
  • Required: A list of input parameters for the method, separated by commas, each preceded by its data type, and enclosed in parentheses (). If there are no parameters, use a set of empty parentheses. A method can only have 32 input parameters.
  • Required: The body of the method, enclosed in braces {}. All the code for the method, including any local variable declarations, is contained here.
Use the following syntax when defining a method:
[public | private | protected | global] [override] [static] data_type method_name 
(input parameters) 
{
// The body of the method
}
Note

Note

You can only use override to override methods in classes that have been defined as virtual.

For example:
  public static Integer getInt() { 
     return MY_INT; 
  }

As in Java, methods that return values can also be run as a statement if their results are not assigned to another variable.

Note that user-defined methods:
  • Can be used anywhere that system methods are used.
  • Can be recursive.
  • Can have side effects, such as DML insert statements that initialize sObject record IDs. See Apex DML Statements.
  • Can refer to themselves or to methods defined later in the same class or anonymous block. Apex parses methods in two phases, so forward declarations are not needed.
  • Can be polymorphic. For example, a method named foo can be implemented in two ways, one with a single Integer parameter and one with two Integer parameters. Depending on whether the method is called with one or two Integers, the Apex parser selects the appropriate implementation to execute. If the parser cannot find an exact match, it then seeks an approximate match using type coercion rules. For more information on data conversion, see Understanding Rules of Conversion.
    Note

    Note

    If the parser finds multiple approximate matches, a parse-time exception is generated.

  • When using void methods that have side effects, user-defined methods are typically executed as stand-alone procedure statements in Apex code. For example:
    System.debug('Here is a note for the log.');
  • Can have statements where the return values are run as a statement if their results are not assigned to another variable. This is the same as in Java.

Passing Method Arguments By Value

In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments are lost.

Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method returns, the passed-in argument still references the same object as before the method call and can't be changed to point to another object. However, the values of the object's fields can be changed in the method.

The following are examples of passing primitive and non-primitive data type arguments into methods.

Example: Passing Primitive Data Type Arguments

This example shows how a primitive argument of type String is passed by value into another method. The debugStatusMessage method in this example creates a String variable, msg, and assigns it a value. It then passes this variable as an argument to another method, which modifies the value of this String. However, since String is a primitive type, it is passed by value, and when the method returns, the value of the original variable, msg, is unchanged. An assert statement verifies that the value of msg is still the old value.
public class PassPrimitiveTypeExample {
    public static void debugStatusMessage() {
        String msg = 'Original value';
        processString(msg);
        // The value of the msg variable didn't
        // change; it is still the old value.
        System.assertEquals(msg, 'Original value');
    }
    
    public static void processString(String s) {
        s = 'Modified value';
    }
}

Example: Passing Non-Primitive Data Type Arguments

This example shows how a List argument is passed by value into another method and can be modified. It also shows that the List argument can’t be modified to point to another List object. First, the createTemperatureHistory method creates a variable, fillMe, that is a List of Integers and passes it to a method. The called method fills this list with Integer values representing rounded temperature values. When the method returns, an assert verifies that the contents of the original List variable has changed and now contains five values. Next, the example creates a second List variable, createMe, and passes it to another method. The called method assigns the passed-in argument to a newly created List that contains new Integer values. When the method returns, the original createMe variable doesn’t point to the new List but still points to the original List, which is empty. An assert verifies that createMe contains no values.
public class PassNonPrimitiveTypeExample {
    
    public static void createTemperatureHistory() {
        List<Integer> fillMe = new List<Integer>();        
        reference(fillMe);
        // The list is modified and contains five items
        // as expected.
        System.assertEquals(fillMe.size(),5);        
        
        List<Integer> createMe = new List<Integer>();
        referenceNew(createMe);
        // The list is not modified because it still points
        // to the original list, not the new list 
        // that the method created.
        System.assertEquals(createMe.size(),0);     
    }
            
    public static void reference(List<Integer> m) {
        // Add rounded temperatures for the last five days.
        m.add(70);
        m.add(68);
        m.add(75);
        m.add(80);
        m.add(82);
    }    
        
    public static void referenceNew(List<Integer> m) {
        // Assign argument to a new List of
        // five temperature values.
        m = new List<Integer>{55, 59, 62, 60, 63};
    }    
}
Previous
Next