Skip to main content
What is the difference  between static , public and private members of a class,? when we invoke class from trigger? Can anyone pls explain this with the help of an example.

when we invoke class with (static , public, private member) from trigger
6 个回答
  1. 2015年1月11日 19:16
    These are all the same as when refering to Java classes [1][2].

    static

    Static methods (and variables) can be used without instantiating a new instance of the class

     

    public class Utils {

    public static String getHelloWorld() {

    return 'Hello World';

    }

    }

    These methods can be called directly

     

    String salutation = Utils.getHelloWorld();

     

    non-static

    Non-static method (and variables) must have a new instance of the class instantiated in order to be used.  Typically these rely on data inside the class that then is refered to inside the class

     

    public class Utils {

    private lang;

    public Utils() {

    lang = 'en';

    }

    public Utils(String lang) {

    this.lang = lang;

    }

    public String getHelloWorld() {

    if (lang == 'en') {

    return 'Hello World';

    } else if (lang == 'es') {

    return 'Hola Mundo';

    }

      // Return esperanto if we don't know the language

    return 'Saluton Mondo';

    }

    }

    This version of the method requires us to create a new instance

     

    Utils en_utils = new Utils();

    String salutation_en = en_utils.getHelloWorld();

    // salutation_en == 'Hello World'

    Utils es_utils = new Utils('es');

    String salutation_es = es_utils.getHelloWorld();

    // salutation_es == 'Hola Mundo'

    Utils fr_utils = new Utils('fr');

    String salutation_fr = fr_utils.getHelloWorld();

    // salutation_fr == 'Saluton Mondo'

    In this example, we can see that we have a 

    private class level variable lang that we use inside of getHelloWorld.  Because this variable is private, we cannot reference it outside of class level variables.  We can mix and match these.  For example, we can have a public class level method call a private class level method that then uses / sets both private and public variables.  We can only call public variables and methos from outside the class

     

    [1] http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

    [2] http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html