Static and Instance

In Apex, you can have static methods, variables, and initialization code. Apex classes can’t be static. You can also have instance methods, member variables, and initialization code (which have no modifier), and local variables:

The following is an example of a local variable whose scope is the duration of the if code block:

Boolean myCondition = true;
if (myCondition) {
    integer localVariable = 10;

Using Static Methods and Variables

You can only use static methods and variables with outer classes. Inner classes have no static methods or variables. A static method or variable does not require an instance of the class in order to run.

All static member variables in a class are initialized before any object of the class is created. This includes any static initialization code blocks. All of these are run in the order in which they appear in the class.

Static methods are generally used as utility methods and never depend on a particular instance member variable value. Because a static method is only associated with a class, it cannot access any instance member variable values of its class.

Static variables are only static within the scope of the request. They’re not static across the server, or across the entire organization.

Use static variables to store information that is shared within the confines of the class. All instances of the same class share a single copy of the static variables. For example, all triggers that are spawned by the same transaction can communicate with each other by viewing and updating static variables in a related class. A recursive trigger might use the value of a class variable to determine when to exit the recursion.

Suppose you had the following class:

public class p { 
   public static boolean firstRun = true; 

A trigger that uses this class could then selectively fail the first run of the trigger:

trigger t1 on Account (before delete, after delete, after undelete) { 
                 Trigger.old[0].addError('Before Account Delete Error');

Static variables defined in a trigger don’t retain their values between different trigger contexts within the same transaction, for example, between before insert and after insert invocations. Define the static variables in a class instead so that the trigger can access these class member variables and check their static values.

Class static variables cannot be accessed through an instance of that class. So if class C has a static variable S, and x is an instance of C, then x.S is not a legal expression.

The same is true for instance methods: if M() is a static method then x.M() is not legal. Instead, your code should refer to those static identifiers using the class: C.S and C.M().

If a local variable is named the same as the class name, these static methods and variables are hidden.

Inner classes behave like static Java inner classes, but do not require the static keyword. Inner classes can have instance member variables like outer classes, but there is no implicit pointer to an instance of the outer class (using the this keyword).

For Apex saved using Salesforce API version 20.0 or earlier, if an API call causes a trigger to fire, the chunk of 200 records to process is further split into chunks of 100 records. For Apex saved using Salesforce API version 21.0 and later, no further splits of API chunks occur. Note that static variable values are reset between API batches, but governor limits are not. Do not use static variables to track state information between API batches.

Using Instance Methods and Variables

Instance methods and member variables are used by an instance of a class, that is, by an object. Instance member variables are declared inside a class, but not within a method. Instance methods usually use instance member variables to affect the behavior of the method.

Suppose you wanted to have a class that collects two dimensional points and plot them on a graph. The following skeleton class illustrates this, making use of member variables to hold the list of points and an inner class to manage the two-dimensional list of points.

public class Plotter {

    // This inner class manages the points
    class Point { Double x; Double y; Point(Double x, Double y) { this.x = x; this.y = y; } Double getXCoordinate() { return x; } Double getYCoordinate() { return y; } } List<Point> points = new List<Point>(); public void plot(Double x, Double y) { points.add(new Point(x, y)); } // The following method takes the list of points and does something with them
    public void render() { } }

Using Initialization Code

Instance initialization code is a block of code in the following form that is defined in a class:


   //code body


The instance initialization code in a class is executed every time an object is instantiated from that class. These code blocks run before the constructor.

If you do not want to write your own constructor for a class, you can use an instance initialization code block to initialize instance variables. However, most of the time you should either give the variable a default value or use the body of a constructor to do initialization and not use instance initialization code.

Static initialization code is a block of code preceded with the keyword static:

static {

   //code body


Similar to other static code, a static initialization code block is only initialized once on the first use of the class.

A class can have any number of either static or instance initialization code blocks. They can appear anywhere in the code body. The code blocks are executed in the order in which they appear in the file, the same as in Java.

You can use static initialization code to initialize static final variables and to declare any information that is static, such as a map of values. For example:

public class MyClass {
    class RGB {

        Integer red;
        Integer green;
        Integer blue;

        RGB(Integer red, Integer green, Integer blue) {
   = red;
   = green;
   = blue;

   static Map<String, RGB> colorMap = new Map<String, RGB>();

    static {
        colorMap.put('red', new RGB(255, 0, 0));
        colorMap.put('cyan', new RGB(0, 255, 255));
        colorMap.put('magenta', new RGB(255, 0, 255));
© Copyright 2000–2015, inc. All rights reserved.
Various trademarks held by their respective owners.