Access Modifiers in Salesforce Apex Classes

In Salesforce Apex, we define the access level of Apex classes using access modifiers, which are also referred to as access specifiers. These modifier keywords define the visibility and accessibility of classes and their members (methods and variables).

They help implement encapsulation, maintain the application’s security, and controlling how and where the code can be accessed and modified.

In this Salesforce tutorial, we will learn about all the Access modifiers in Apex and their use cases in Apex classes.

What are Access Modifiers in Salesforce Apex?

In Salesforce Apex, access modifiers, also known as access specifiers, are keywords used in Apex code to set the level of access to classes and class members. The encapsulated code of the Apex class in access modifiers decides its access, ensuring that sensitive information is not exposed to unauthorized sections of the program or other applications.

There are four types of Access Modifiers in Salesforce Apex:

  • Public
  • Private
  • Protected
  • Global

Use Access Modifiers in Salesforce Apex Classes

Now, we will discuss all four Apex access modifiers and their use case in Salesforce Apex Classes.

1. Public Access Modifier in Apex

In Salesforce Apex, methods or variables declared as public in a class are accessible throughout the application, including other classes and triggers. Public access is commonly used when a method or variable needs to be accessed across different classes.

Here is an example of using the public access modifier in Apex Classes.

public class MyClass
           { public Integer myNumber = 50; 

             public void showNumber() { 
                        System.debug('My number is: ' + myNumber);
           }
}

Let’s take a use case example, where we will create a utility class to retrieve active accounts. This class will have a public method that queries accounts where the Is_VIP__c custom checkbox field is checked. Another class will then use this method to get the VIP accounts.

Class with Public method:

public class AccountUtility {
    public static List<Account> getVIPAccounts() {
      
        List<Account> VIPAccounts = [SELECT Id, Name, Industry FROM Account WHERE Is_VIP__c = true];
        return VIPAccounts;
    }
}

In the above code, the getActiveAccounts method is public and static, allowing us to call it directly without creating an instance of AccountUtility. The method returns a list containing active accounts by checking accounts where Is_VIP__c is true.

Create a Class to call the Public method:

public class AccountManager {
    public static void displayVIPAccounts() {
        List<Account> VIPAccounts = AccountUtility.getVIPAccounts();
        
        for (Account acc : VIPAccounts) {
            System.debug('Account Name: ' + acc.Name + ', Industry: ' + acc.Industry);
        }
    }
}

In the method displayVIPAccounts, we will call the AccountUtility.getVIPAccounts() public method to retrieve the list of active accounts by executing the code below in Apex anonymous.

AccountManager.displayActiveAccounts();

Output:

Call Public Class in Salesforce Apex

This way, we can call the Public methods in other classes using the above call method.

2. Private Access Modifier in Apex

In Salesforce Apex, methods or variables declared private in a class by default ensure that the method is accessible only within the defining class. This level is crucial for hiding the class’s internal workings from the other classes.

For example, we have a public class called DiscountManager that generates and sends discount codes to customers (accounts). We want only specific methods to be accessible externally while keeping the logic to create the code hidden. We can apply this restriction by using the private access modifier.

public class DiscountManager {
    private String discountCode;
    
    private String generateDiscountCode() {
        discountCode = 'DISC-' + String.valueOf(Math.random()).substring(2, 6);
        return discountCode;
    }

    public void sendDiscountToCustomer(Id customerId) {
        String code = generateDiscountCode();
        
        System.debug('Sending discount code ' + code + ' to customer: ' + customerId);
    }
}

In the above code, we have marked the method generateDiscountCode() as private, restricting its use outside the class.

Anonymous code to call the class method:

DiscountManager discountManager = new DiscountManager();
Id customerId = '001J3000007zBCKIA2'; // Account Id
discountManager.sendDiscountToCustomer(customerId);

Output:

Use Private method in Salesforce Class

When we called the method within the class, the code was executed successfully, and the output was returned as expected.

Let’s see what error we will face while calling this private method in any other class.

DiscountManager discountManager = new DiscountManager();
String code = discountManager.generateDiscountCode();
System.debug('Discount Code: ' + code);

In the above apex code, String code = discountManager.generateDiscountCode(); tries to call generateDiscountCode() directly, which is not allowed because the method is private.

Output:

Unable to call private method in Salesforce Apex

3. Protected Access Modifier in Apex

In Salesforce Apex, when we create a method with Protected Access, it is accessible within the defining class and any subclasses (inherited classes), regardless of whether these subclasses are in the same application, but only if the subclass is in the same namespace. This specifier is helpful for object-oriented practices like inheritance.

In this example, we will create a public class Calculator and define a method to calculate the square of numbers within that class. This method will be calculated using the Protected access modifier so that it can be accessible to the extended classes.

Apex Code for Parent Class:

public virtual class Calculator {
    protected Integer calculateSquare(Integer mynumber) {
        return mynumber * mynumber;
    }
    public Integer add(Integer num1, Integer num2) {
        return num1 + num2;
    }
}

In the above code, we have used virtual in the public class, which allows the class to extend into another class. The method to calculate the square of integers is in the Protected identifier.

Subclass to access Protected Method:

public class ScientificCalculator extends Calculator {
    public void displaySquare(Integer mynumber) {
        Integer square = calculateSquare(mynumber); 
        System.debug('Square of ' + mynumber + ' is: ' + square);
    }
}

In the above code, we have used the extends keyword, which extends the Calculator class in the current class. Then, using “Integer square = calculateSquare(mynumber),” we accessed the protected method of calculating squares from the parent class.

Call the class method in the anonymous Apex code:

ScientificCalculator sciCalc = new ScientificCalculator();
sciCalc.displaySquare(5);

Output:

Protected Access Identifier in Salesforce Apex

As we can see, the output returned the square of the input integer values. Here, we have successfully called the protected method from the parent class to the subclass.

This way, we can use the Protected access modifiers in Salesforce Apex classes to restrict the method access outside the subclasses.

4. Global Access Modifier in Apex

In Salesforce Apex classes, the Global keyword enables the class method or variable to be used by any Apex code that has access to the class, regardless of the namespace or context. This means that external Salesforce organizations can access global methods.

This access identifier is useful when working with APIs, as all methods used by the API require global access.

It is recommended to use the Global access modifier rarely, too, when required, because cross-application dependencies are difficult to maintain.

Apex Class with Global Access:

For example, we have created a managed package that needs to be accessible by any Salesforce org that installs it. To enable this, you would use the global modifier, making the class and its methods available outside the package.

Here, we have created a global class to calculate tax, which can be accessed anywhere, both inside and outside the system.

Global Apex Class:

global class utility {
    global static Decimal calculateTax(Decimal amount) {
        Decimal taxRate = 0.15; 
        return amount * taxRate;
    }
}

Anonymous code:

Decimal amount = 1000.00;
Decimal tax = Utility.calculateTax(amount); // global method
System.debug('Tax for amount ' + amount + ' is: ' + tax); 

Output:

How to define Global classes in Salesforce

Call the Global method in the external Class:

Now, we will create a public class OrderManager, and there we will use the global method Utility.calculateTax(amount) to calculate the tax on the product price.

public class OrderManager {
  
    public Decimal calculateTotalWithTax(Decimal orderAmount) {
        Decimal tax = Utility.calculateTax(orderAmount); // global method
        Decimal totalAmount = orderAmount + tax;
        return totalAmount;
    }

    public void displayOrderDetails(Decimal orderAmount) {
        Decimal totalAmount = calculateTotalWithTax(orderAmount);
        System.debug('Order Amount: ' + orderAmount);
        System.debug('Total Amount with Tax: ' + totalAmount);
    }
}

To call the class method, we will use the below Apex anonymous code.

OrderManager orderManager = new OrderManager();
Decimal orderAmount = 1500.00;
orderManager.displayOrderDetails(orderAmount); 

Output:

Global access modifiers in Salesforce Apex

This way, we can use the global access modifiers in Salesforce Apex classes and the global methods in external classes and systems.

Conclusion:

In this Salesforce Apex tutorial, we learned about access modifiers or access specifiers. We discussed the use cases of all the modifiers: public, private, protected, and global, and we successfully implemented them in the Apex classes, defining the class or method access level.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.