Static Keyword
In Apex (and other object-oriented languages like Java), the static keyword is used
to indicate that a method, variable, or block belongs to the class itself rather than to
instances of the class.
Key Concepts of static:
Class-Level Association:
1. When you declare a method or variable as static, it belongs to the class itself,
not to any particular object or instance of the class.
2. This means you can call a static method or access a static variable without
creating an object of the class.
Example:
public class Car {
public static String brand = 'TATA'; // Static variable
public static void showBrand() { // Static method
[Link](brand);
}
}
// No need to create an instance of Car to call the static method
[Link](); // Outputs: TATA
Shared Across All Instances:
1. Static variables are shared across all instances of a class. If you change the value of a
static variable, that change is reflected across all instances of the class.
Example:
public class Car {
public static String brand = 'TATA';
}
[Link] = 'Tesla'; // Changing the static variable
[Link]([Link]); // Outputs: Tesla for all instances of the class
Static Methods:
A static method can only access static variables or other static methods directly. It
cannot access instance variables (non-static) because instance variables are tied to
individual objects, not the class as a whole.
Static methods are often used when behavior or functionality is general and does
not depend on specific object state (i.e., it’s the same for all instances).
Example:
public class MathUtils {
public static Integer add(Integer a, Integer b) {
return a + b;
}
}
// Usage without needing an instance
Integer result = [Link](5, 10); // Outputs: 15
When to Use static:
Use static when the data or behavior is not tied to any specific instance of a class. For
example:
1. Utility methods (e.g., [Link])
2. Constants or configurations that apply to the class as a whole
3. Caching values that are shared across instances
Summary:
static members belong to the class, not to any instance.
static methods can only interact with other static members.
static members are shared across all instances of the class, and changes to them are
reflected globally.