“Static” Keyword In Salesforce

Introduction

In Apex, we have static variables, methods, and initialization static blocks with instance variables, methods, and initialization code. But our Apex classes can’t be static. Static variables and methods are only used with outer classes, not with inner classes. They don’t require an instance to run. In this article we will learn more about “Static” Keyword In Salesforce.

Static Variables in Salesforce

Values of Static variables will be shared among multiple instances of a class since they belong to a class and can be directly called with the class name. In other words, all the instances of a class share a single copy of a class. Static variables are initialized only once which gets the memory at compile time

We can use static variables when their value is independent of the instance, and only one copy of a class is required. The static keyword is used to declare any variable as static.

It is also used to avoid recursive triggers.

To access static variables, we don’t require the object of a class. We can directly call them with the help of the class name.

Syntax:

Classname.variableName

Static Methods in Salesforce

We need not instantiate a new instance of a class for static methods. It is initialized only once when a class is loaded. It acts as a utility method that doesn’t depend on the instance variable value since the static method belongs to a class.

We can’t use non-static variables within a static method.

Syntax:

Classname.methodName

Example of static variable and method

public class Covid19
{
private Integer recoveredInArea = 0;
//static variable
public static Integer recoveredInCountry = 0;
public void treatPatient()
{
recoveredInArea++;
recoveredInCountry++;
}
// static method
public static void printTreatedPeople(){
System.debug('Recovered in country : '+recoveredInCountry);
}
}

 

Anonymous Window

Covid19 nagpur = new Covid19();
System.debug(‘Number of People recovered in Nagpur: ’ + nagpur.recoveredInArea);
Covid19. printTreatedPeople();
System.debug(‘Number of People recovered in country: ’ + Covid19.recoveredInCountry);
nagpur.treatPatient();
System.debug(‘Number of People recovered in Nagpur: ’ + nagpur.recoveredInArea);
Covid19. printTreatedPeople();
System.debug(‘Number of People recovered in country: ’ + Covid19.recoveredInCountry);

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.