public class A {
Boolean B;
static Boolean C;
public Boolean getB() {
return B;
}
public void setB(Boolean value) {
b = value;
}
public static Boolean getC() {
return C;
}
public static void setC(Boolean value) {
C = value;
}
}
public class D {
public void E() {
A.setC(true);
System.assert(A.getC());
A F = new A(), G = new A();
F.setB(true);
G.setB(false);
System.assert(F.getB());
System.assert(!G.getB());
}
}
This example illustrates the use of both instance
and static
members. Here, D
can access A
through the use of instances F
and G
. It also has access to A
's static
methods, getC()
and setC()
. Use instances when you need to keep track of multiple independent versions of data, and use static members when the data does not need to be tracked independently. This reduces code verbosity, since you no longer have to instantiate classes just to use their methods.
Examples of instance
uses:
- Wrapper classes.
- Controllers.
- Data to be serialized in the view state.
Examples of instance methods from the standard library include:
List.Sort()
String.Substring()
EmailAttachment.setBody()
Examples of static
uses:
- Utility methods.
- Factory methods (factories create instances in a controlled manner).
- Singleton classes (classes that may only ever have one instance at a time).
- Functions that operate on their input and do not store the results.
Examples of static methods from the standard library include:
String.valueOf()
Date.newInstance()
EncodingUtil.base64Encode()
Consider how the code is going to be used before you construct it. Use static
utility methods whenever possible, and use instance
methods only when it makes sense.