Access modifiers are used in apex class in salesforce. Similar to Java programming, Salesforce supports 4 different access modifiers in salesforce.
- This is default modifier, if no access modifiers are mentioned then it will be by default private.
- Method or variable is accessible ONLY within the Apex class in which it is defined.
- The method or variable is visible to any inner classes in the defining Apex class.
- The method or variable is also visible to class that extend the defining Apex class.
- You can only use this access modifier for instance methods and member variables.
- It is strictly more permissive than the default (private) setting, just like Java.
- The method or variable can be used by any Apex in this application or namespace.
- The public access modifier is not the same as it is in Java.
- This was done to keep the code for each application separate.
- If you want Java kind of access modifiers, then User global access modifiers.
- The method or variable can be used by any Apex code that has access to the class.
- This is accessible to any application, including third party applications.
- If any method or variable is declared global, then its class should also be global.
- If any business logic should be allowed to be executed by any third-party application, then class and method should be defined as global. Like in SOAP API or Rest API or another apex class.
- global modifiers should be used rarely as its open to all kind of modifier.
- Cross-application dependencies are difficult to maintain.
Syntax: (Shown here as Access_Modifier)
// Public access modifier string variable. public string a_String_Variable; //private access modifier integer variable. private integer a_Integer_Variable; //protected access modifier double variable. protected double a_Protected_Variable;