Saturday, April 8, 2023

Static Variables and Static Methods in Apex

Static variables are variables that belong to an overall class, not a particular object of a class. Think of a static variable to be like a global variable – its value is shared across your entire org. Any particular object’s properties or values are completely irrelevant when using static. When a class containing static variables is first referenced, the static variables are initialized. The initialization process occurs only once per execution context, regardless of how many times the class is referenced.

This example illustrates static vs. non-static variables

public class classexmple {
  public Integer count = 0;
  public static Integer Scount = 0;
  public void executeMethod() {
    count = count + 1;
    Scount = Scount + 1;
  }
classexmple obj1 = new classexmple();
classexmple obj2 = new classexmple();
obj1.executeMethod();
obj2.executeMethod();
System.debug(obj1.count); // This is 1
System.debug(obj2.count); // This is 1
// Access static variables only by class name, 
not object name
System.debug(classexmple.Scount); // This is 2

Static methods, similarly, are methods that act globally and not in the context of a particular object of a class. Being global, static methods only have access to its provided inputs and other static (global) variables.

This example illustrates static vs. non-static methods

public class SecondExample {
  public void Method1() {
    // code
  }
  public static String Method2() {
    // code
    String a;
    return a;
  }
  public static String Method3(String param) {
    String a;
    //code
    return a;
  }
}

SecondExample obj = new SecondExample();
// Non-static methods require an object 
for context
obj.method1();
// Static methods aren't related to a 
particular object
// You don't even use an object to call a 
static method!
SecondExample.Method2();
SecondExample.Method3('value');


Let me know your thoughts in the comment section!!

No comments:

Post a Comment

Mostly Viewed