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.

  1. Optional : Modifiers such as public or final as well as static.
  2. Required : The data type of the variable, such as String or Boolean.
  3. Optional : The value of the variable.
  4. Optional : The name of the variable.
</>
Copy
 
[public | private | protected | global | final] [static] data_type Variable_name

Example

</>
Copy
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.

</>
Copy
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 typeHow it is accessedCommon use
Instance variableThrough an object, such as obj.nameStores state that belongs to one object instance.
Static variableThrough the class name, such as ClassName.valueStores class-level data, constants, or values shared within the transaction.
Local variableInside the method or block where it is declaredStores temporary data used only during method execution.
</>
Copy
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 modifierMeaning in Apex class design
privateAccessible only inside the class where it is declared. This is the default for inner class members when no access modifier is specified.
publicAccessible from Apex code in the same namespace.
protectedAccessible by the defining class and subclasses.
globalAccessible across namespaces. Use it only when a managed package or external access requirement needs it.
staticBelongs to the class rather than an object instance.
finalUsed when a value should not be reassigned after initialization.

Class Methods

To define a method specify the following

  1. 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.
  2. 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.
  3. A method can only have 32 input parameters.
  4. Required : The body of the method, enclosed in braces { }. All the code for the method, including any local variable declarations is contained base.

Syntax

</>
Copy
(public | private | protected | global ) [Override] [static] data_type Variable_name
(input parameters)

Example

</>
Copy
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.

</>
Copy
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 typeDescriptionSimple example
Instance methodCalled on an object created from a class.obj.updateStatus('Open');
Static methodCalled on the class name without creating an object.DiscountCalculator.calculateDiscount(1000, 10);
ConstructorRuns when an object is created. It has the same name as the class and no return type.new CustomerHelper();
Test methodUsed in Apex test classes to validate code behavior.@isTest static void testMethodName()
Batch Apex methodsUsed 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.

</>
Copy
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.

</>
Copy
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

</>
Copy
Classname objectname = new Classname();

Example

</>
Copy
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.

</>
Copy
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.

TermMeaning in Apex
Apex class objectAn instance created from a user-defined Apex class.
ObjectA general Apex type that can hold different value types, but usually needs casting before type-specific use.
sObjectA Salesforce record representation, such as an Account, Case, Lead, or custom object record.
</>
Copy
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 methodPurpose
startCollects the records or query locator that must be processed.
executeProcesses each batch of records.
finishRuns after all batches are complete, usually for logging, notification, or final processing.
</>
Copy
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 static for 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 global when private or public is enough.
  • Confusing an Apex class object with a Salesforce sObject record.
  • 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 void behavior.
  • The object section explains both Apex class objects and Salesforce sObject records without mixing the two.
  • Batch Apex is mentioned only as a special class pattern with start, execute, and finish methods.
  • New syntax examples use Apex-style code and are marked with PrismJS-compatible language classes.