In Apex, understanding the difference between static and instance context is crucial for designing efficient and maintainable code.
🔹 What is Static Context?
A static variable or method belongs to the class itself, not to any specific instance (object) of that class. You don’t need to create an object to use a static member.
Example: Static Method & Variable
public class Utils {
public static Integer count = 0;
public static void logMessage(String msg) {
System.debug('Log: ' + msg);
count++;
}
}
Usage:
Utils.logMessage('Start process');
System.debug(Utils.count); // Output: 1
🔹 What is Instance Context?
An instance variable or method belongs to an object created from a class. You need to create an object to use instance members.
Example: Instance Method & Variable
public class Person {
public String name;
public Person(String name) {
this.name = name;
}
public void sayHello() {
System.debug('Hello, I am ' + name);
}
}
Usage:
Person p = new Person('John');
p.sayHello(); // Output: Hello, I am John
🔍 Key Differences
Feature | Static | Instance |
---|---|---|
Belongs To | Class | Object |
Accessed Using | Class name | Object reference |
Memory Allocation | Once per class | Each time object is created |
Example | Utils.logMessage() |
p.sayHello() |
🧠 Best Practices
- Use static when the behavior or data doesn't depend on object state (e.g., utility functions).
- Use instance when behavior varies per object (e.g., user-specific logic).