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 are not as useful in smaller portions of Apex. For example, declaring a method as global in an anonymous block does not enable you to call it from outside of that code.
For more information on class access modifiers, see Apex Defining Classes.
By default, a method or variable is visible only to the Apexwithin the defining class. This is different from Java, where methods and variables are public by default. Apex is more restrictive, and requires you to 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:
To use the private, protected, public, or global access modifiers, use the following syntax:
[(none)|private|protected|public|global] declaration
For example:
private string s1 = '1'; public string gets1() { return this.s1; }