Access Modifiers
Understanding Access Modifiers in Apex
Access modifiers in Apex control the visibility and accessibility of classes, methods, and variables within your Salesforce application. Apex provides four main types of access modifiers:
privateprotectedpublicglobal
Let’s explore each one with simple examples to understand how and when to use them.
1) global Access Modifier
When you mark a class or method as global, it can be accessed from anywhere, even outside the current application or namespace. This is often used when exposing your Apex code to external systems, like through a SOAP API.
Important: If a method or variable is declared global, the class must also be marked global.
global class AppConnector {
global String getStatus() {
return 'Connected';
}
}
Here, getStatus() can be accessed by any Apex code that can see the AppConnector class — even outside your org.
2) public Access Modifier
A public method or variable is accessible only within your application or namespace. It cannot be accessed from other packages or through APIs.
Unlike Java, where public means completely open access, Apex uses global to achieve Java-like public behavior.
public class AccountHandler {
public void printAccountName() {
System.debug('Account: ABC Corp');
}
}
In the above example, any class within the same application can call printAccountName().
3) protected Access Modifier
The protected modifier allows access within the same class and any class that extends it. This is useful when you want to allow inherited behavior but keep the method hidden from the rest of the code.
public class BaseLogger {
protected String getLogPrefix() {
return '[LOG]: ';
}
}
public class ErrorLogger extends BaseLogger {
public void logError(String message) {
System.debug(getLogPrefix() + message);
}
}
Here, getLogPrefix() is accessible inside ErrorLogger because it extends BaseLogger.
4) private Access Modifier (Default)
When no access modifier is specified, private is used by default. This means the method or variable can be accessed only inside the class where it is defined.
public class UserData {
private String secretKey = 'abc123';
public void showKey() {
System.debug('Secret Key: ' + secretKey);
}
}
Here, secretKey is private and cannot be accessed from outside the UserData class.
Summary
| Modifier | Accessible From | Inheritable | External Access |
private | Inside the same class only | ❌ | ❌ |
protected | Same class and child classes | ✅ | ❌ |
public | Same namespace or application | ❌ | ❌ |
global | Anywhere (including outside the org) | ✅ | ✅ |
Key Notes:
Always use the minimum access level needed.
For API integrations or managed packages, prefer
global.For internal utility classes,
privateorpublicis often enough.Use
protectedif you plan to extend the class in future.

