Apex Class Variables
In this Salesforce tutorial, we will learn about Apex Class Variables, class methods and objects.
In Apex, a class is a blueprint that contains variables and methods. A variable stores data for the class or method. A method performs an action and can return a value. An object is an instance of a class created with the new keyword, except when you are working with static members that belong to the class itself.
Apex syntax is similar to Java, but it runs on the Salesforce platform and follows Salesforce governor limits, sharing rules, and data access rules. When you create Apex class variables and methods, always choose the correct access modifier, data type, static or instance behavior, and return type.
Apex class variable declaration format
The variables in the class should specify the following properties when they are defined.
- Optional : Modifiers such as public or final as well as static.
- Required : The data type of the variable, such as String or Boolean.
- Optional : The value of the variable.
- Optional : The name of the variable.
[public | private | protected | global | final] [static] data_type Variable_name
Example
private Static final Integer My_INT;
private final Integer i=5;
In practical Apex code, variable names are case-sensitive and should be clear. Constants are usually declared with static final, and instance variables are declared without static when each object needs its own value.
public class AccountCounter {
private static final Integer DEFAULT_LIMIT = 100;
private Integer processedCount = 0;
public String statusMessage = 'Not started';
}
Instance variables and static variables in Apex classes
An instance variable belongs to one object created from the class. A static variable belongs to the class itself and is accessed by using the class name. This difference is important because static members are commonly used in utility classes, constants, and helper methods that do not need object state.
| Apex variable type | How it is accessed | Common use |
|---|---|---|
| Instance variable | Through an object, such as obj.name | Stores state that belongs to one object instance. |
| Static variable | Through the class name, such as ClassName.value | Stores class-level data, constants, or values shared within the transaction. |
| Local variable | Inside the method or block where it is declared | Stores temporary data used only during method execution. |
public class ScoreTracker {
public static Integer totalRuns = 0;
public Integer playerRuns = 0;
public void addRuns(Integer runs) {
playerRuns += runs;
totalRuns += runs;
}
}
In the above Apex example, playerRuns is different for each object, while totalRuns is a class-level value accessed as ScoreTracker.totalRuns.
Apex access modifiers for class variables and methods
Apex access modifiers define where a variable or method can be used. Choose the narrowest access level that satisfies the requirement. This keeps the class easier to maintain and reduces unintended use from other code.
| Apex modifier | Meaning in Apex class design |
|---|---|
private | Accessible only inside the class where it is declared. This is the default for inner class members when no access modifier is specified. |
public | Accessible from Apex code in the same namespace. |
protected | Accessible by the defining class and subclasses. |
global | Accessible across namespaces. Use it only when a managed package or external access requirement needs it. |
static | Belongs to the class rather than an object instance. |
final | Used when a value should not be reassigned after initialization. |
Class Methods
To define a method specify the following
- Optional : The data type of the value returned by the method, Such as String or Integer use void if the method does not return a value.
- Required : A list of input parameter for the method separated by commas, each preceded by its data type, and enclosed in parentheses(). If there are not parameters, use a set of empty parentheses.
- A method can only have 32 input parameters.
- Required : The body of the method, enclosed in braces { }. All the code for the method, including any local variable declarations is contained base.
Syntax
(public | private | protected | global ) [Override] [static] data_type Variable_name
(input parameters)
Example
public Static Integer getInt() {
return My-INT;
}
An Apex method normally contains an access modifier, optional keywords such as static or override, a return type, method name, parameters, and a method body. Use void when the method performs an action but does not return a value.
public class DiscountCalculator {
public static Decimal calculateDiscount(Decimal amount, Decimal percentage) {
return amount * percentage / 100;
}
public void updateStatus(String newStatus) {
System.debug('Status changed to ' + newStatus);
}
}
Different methods in Apex classes
Apex classes can contain different kinds of methods depending on the requirement. The most common method types are instance methods, static methods, constructors, test methods, and methods required by Salesforce interfaces such as Batch Apex.
| Apex method type | Description | Simple example |
|---|---|---|
| Instance method | Called on an object created from a class. | obj.updateStatus('Open'); |
| Static method | Called on the class name without creating an object. | DiscountCalculator.calculateDiscount(1000, 10); |
| Constructor | Runs when an object is created. It has the same name as the class and no return type. | new CustomerHelper(); |
| Test method | Used in Apex test classes to validate code behavior. | @isTest static void testMethodName() |
| Batch Apex methods | Used in a class that implements Database.Batchable. | start, execute, and finish. |
Static Apex utility class example
A utility class usually groups reusable helper methods. Such methods are often declared as static because they do not need object-specific state.
public class TextUtil {
public static Boolean isBlankValue(String value) {
return value == null || value.trim().length() == 0;
}
}
The static method can be called directly with the class name.
Boolean result = TextUtil.isBlankValue('');
Object
Object is a instance of a class. This has both State and behaviour. Memory for the data members are allocated only when you create a object.
Syntax
Classname objectname = new Classname();
Example
Class example {
\\code
}
Example e = new Example();
In Apex, an object is created from a class by using the new keyword. Once the object is created, you can access its public instance variables and call its public instance methods. Static methods do not require an object.
public class GreetingService {
public String name;
public GreetingService(String customerName) {
name = customerName;
}
public String getMessage() {
return 'Hello ' + name;
}
}
GreetingService service = new GreetingService('Ravi');
String message = service.getMessage();
Apex Object class and Salesforce sObject records
The word object can mean different things in Apex. A normal Apex object is an instance of an Apex class. The Object type is the base type for values when the exact type is not known at compile time. A Salesforce sObject is a record type such as Account, Contact, or a custom object record.
| Term | Meaning in Apex |
|---|---|
| Apex class object | An instance created from a user-defined Apex class. |
Object | A general Apex type that can hold different value types, but usually needs casting before type-specific use. |
sObject | A Salesforce record representation, such as an Account, Case, Lead, or custom object record. |
Account acc = new Account(Name = 'Acme Corporation');
Object value = acc.Name;
String accountName = (String) value;
Batch Apex class methods: start, execute, and finish
A Batch Apex class is a special Apex class used to process large data sets in smaller batches. A class that implements Database.Batchable<sObject> contains three main methods: start, execute, and finish.
| Batch Apex method | Purpose |
|---|---|
start | Collects the records or query locator that must be processed. |
execute | Processes each batch of records. |
finish | Runs after all batches are complete, usually for logging, notification, or final processing. |
global class AccountBatchExample implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id, Name FROM Account');
}
global void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account acc : scope) {
acc.Description = 'Processed by batch';
}
update scope;
}
global void finish(Database.BatchableContext bc) {
System.debug('Batch processing completed');
}
}
Common mistakes with Apex variables, methods, and objects
- Using
staticfor data that should belong to each object instance. - Calling an instance method directly with the class name instead of creating an object.
- Returning a value from a method declared as
void. - Forgetting to initialize an object before using its instance variables or methods.
- Using a broad modifier such as
globalwhenprivateorpublicis enough. - Confusing an Apex class object with a Salesforce
sObjectrecord. - Writing methods with too many parameters instead of using a wrapper class or structured input.
FAQ on Apex class variables, methods, and objects
What are variables in Apex?
Variables in Apex are named storage locations used to hold values during code execution. They can be local variables inside a method, instance variables belonging to an object, or static variables belonging to a class.
What are the different methods in Apex?
Common Apex method types include instance methods, static methods, constructors, test methods, and interface-required methods such as Batch Apex start, execute, and finish methods.
What is an object in Apex?
An object in Apex is an instance of a class created with the new keyword. It contains instance variable values and can call instance methods defined in the class.
What is the difference between static and instance variables in Apex?
A static variable belongs to the class and is accessed with the class name. An instance variable belongs to a specific object and is accessed through that object.
What are the different methods of a Batch Apex class?
A Batch Apex class generally contains start, execute, and finish methods. The start method selects records, execute processes records in batches, and finish runs final logic after batch completion.
Editorial QA checklist for Apex class variables tutorial
- The tutorial distinguishes clearly between local variables, instance variables, and static variables.
- The method explanation includes return type, parameters, method body, and
voidbehavior. - The object section explains both Apex class objects and Salesforce
sObjectrecords without mixing the two. - Batch Apex is mentioned only as a special class pattern with
start,execute, andfinishmethods. - New syntax examples use Apex-style code and are marked with PrismJS-compatible language classes.
TutorialKart.com