The reasons for using a static method in Salesforce's Apex are the same as Java or other related object-oriented languages. In short, use static
when the method applies to a class and not an instance of that class. For an example, I'll refer to an answer from not-just-yeti to the question Java: when to use static methods:
In a class Car
you might have a method double convertMpgToKpl(double
mpg)
which would be static, because one might want to know what 35mpg
converts to, even if nobody has ever built a Car. But void
setMileage(double mpg)
(which sets the efficiency of one particular
Car
) can't be static since it's inconceivable to call the method
before any Car
has been constructed.
For more examples, see:
Java: when to use static methods
UPDATE:
I realized this example above might be a little abstract if you're coming to programming and OO design from Salesforce, so let me re-phrase with an example from the built-in Apex TimeZone
class:
This class, as you'd probably expect, represents time zones around the world. Instances of this class (i.e. TimeZone
objects) represent the individual named time zones (e.g. EST, CST, PST, etc). Notice the difference here -- the class defines what a time zone is in general (e.g. a defined region of the earth with a time offset of a particular number of hours), but an instance of the class (i.e. object) defines one particular time zone. For example, the instance for PST would contain data about itself like displayName = "Pacific Standard Time"
and offset = -8
, which you access though its instance methods getDisplayName()
and getOffset()
, respectively. On the other hand, if you wanted to get information about time zones in general, you would use a static
method on the TimeZone
class. For example, Apex defines a static
method called getTimeZone()
on the TimeZone
class you can use to look up a TimeZone
instance by id. To put this together, consider this example to get the display name for PST:
TimeZone pst = TimeZone.getTimeZone('PST'); // static method call
String pstName = pst.getDisplayName(); // instance method call
Notice how the first line is getting an instance of a TimeZone
which has the specific info about PST and then the second line is actually getting that info.
Hopefully this cleared things up and didn't make it more confusing. To sum it up, if you are accessing data or doing something about a particular instance of data, whether that be a car or a time zone, you'll want to use an instance method. On the other hand, if you are accessing data or doing something about a whole class of data, whether it be cars or time zones, you'll want to use a static
method.