Access Modifiers in Apex
Access modifiers will control the visibility of classes, methods and variables in Apex. Selecting the correct access modifier will make sure that code is secure and only accessible where it is required.
Public Modifier
The public modifier lets a class, method or variable to be accessible by any other Apex code in the same namespace or in managed packages, the code is also declared as global if it is in a managed package. Public access is generally used for classes and methods that are considered for common use.
public class Utility {
public static String getGreeting() {
return 'Hello, Salesforce!';
}
}
In the above example, the Utility class and method getGreeting() are accessible to any other code that bring in this class.
Private Modifier
The private modifier restricts access to inside the defining class only. It will be useful for variables and methods that are required to be used only inside the class and not covered outside.
public class Calculator {
// Private method accessible only within this class
private Integer add(Integer a, Integer b) {
return a + b;
}
// Public method that uses the private add method
public Integer getSum(Integer a, Integer b) {
return add(a, b);
}
}
In the above piece of code the method add() is private to make sure that it cannot be accessed directly from outside the class. The public method getSum() uses this private method to perform the addition.
Global Modifier
The global modifier is the top level of access and is useful when we need classes, methods or variables to be accessible within different namespaces, including those in other managed packages. Global modifier is used when developing applications required for broad distribution.
global class GlobalUtility {
global static String getGlobalGreeting() {
return 'Hello from Global Utility!';
}
}
The GlobalUtility class and its method getGlobalGreeting() are accessible from any code, even from outside the package.