Newer Version Available
Access Modifiers
Apex allows you to use the private, protected, public, and global access modifiers when defining methods and variables.
While triggers and anonymous blocks can also use these access modifiers, they aren’t as useful in smaller portions of Apex. For example, declaring a method as global in an anonymous block doesn’t enable you to call it from outside of that code.
For more information on class access modifiers, see Apex Class Definition.
By default, a method or variable is visible only to the Apex code within the defining class. Explicitly specify a method or variable as public in order for it to be available to other classes in the same application namespace (see Namespace Prefix). You can change the level of visibility by using the following access modifiers:
- private
- This access modifier is the default, and means that the method or variable is accessible only within the Apex class in which it’s defined. If you don’t specify an access modifier, the method or variable is private.
- protected
- This means that the method or variable is visible to any inner classes in the defining Apex class, and to the classes that extend the defining Apex class. You can only use this access modifier for instance methods and member variables. This setting is strictly more permissive than the default (private) setting, just like Java.
- public
- This means that the method or variable is accessible by all Apex within a specific package. For accessibility by all second-generation (2GP) managed packages that share a namespace, use public with the @NamespaceAccessible annotation. Using the public access modifier in no-namespace packages implicitly renders the Apex code as @NamespaceAccessible.
- For more information on namespace-based visibility, see Namespace-Based Visibility for Apex Classes in Second-Generation Packages.
- global
- This means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in the same application. This access modifier must be used for any method that must be referenced outside of the application, either in SOAP API or by other Apex code. If you declare a method or variable as global, you must also declare the class that contains it as global.
To use the private, protected, public, or global access modifiers, use the following syntax:
1[(none)|private|protected|public|global] declarationFor example:
1// private variable s1
2private string s1 = '1';
3
4// public method getsz()
5public string getsz() {
6 ...
7}