Thursday, October 18, 2018

static variable in salesforce

Today we will try to cover the topic Static variable in Salesforce.

In apex we have static variables as well as static methods.

static variable in salesforce

Characteristics of static variables:

  • Static variable are global variable which are not related to particular object.
  • Static variable are initialized only once.
  • You can call a static variable directly by class name, similar goes for static methods.
  • Memory is allocated to static variable only once whereas for non static variable memory is allocated every time an instance is created for class.
  • Static variable do not occupy memory in view state.
  • We can use static variables and methods only with outer class they are not allowed with inner class.

Use of static variables:
  • One of the important use of static variable in apex is to avoid trigger recursion which we will see in another topic.
  • To overcome view state error.

Note:We cannot access static variables and static methods from instances of the class.

For ex:

If we have class say testClass,static variable say testVariable,and static method say testMethod.

testClass obj=new testClass();
obj.testVariable  // Is not valid
obj.testMethod  // Is not valid

Instead of the above,

testClass.testVariable  // Is valid
testClass.testMethod // Is valid.

Sample code,

Class testClass{

public static string testVariable=1;
public static string testVariable1;

public static void method1()
system.debug('In method 1');
// Using testVariable in method1


public static void method2()
system.debug('In method 2');
// Calling method1 in method2



static variable in salesforce,static variable in salesforce trigger,static boolean variable in salesforce,global static variable in salesforce,static and nonstatic variable in salesforce,why we use static variable in salesforce,static variable in apex salesforce,declare static variable in salesforce,static variable in salesforce examples,how to access static variable in salesforce,what is static variable in salesforce,use of static variable in salesforce.

No comments:

Post a Comment