Access Modifiers

What Are Access Modifiers in Salesforce Apex?

Apex access modifiers are public, private, protected and global. Learn what each one allows, how the default works, and how they compare with C++ and Java.

On this page
  1. The four Apex access modifiers
  2. A small example
  3. Why global needs care
  4. with sharing is not an access modifier
  5. Comparing with C++ and Java

Access modifiers belong to the Apex language, so the question is really about Apex, the programming language that runs on the Salesforce platform. Apex has four of them: public, private, protected and global. The first three work much as they do in C++. global is the widest level, used when code in other namespaces needs to call in.

The four Apex access modifiers

  • private members are visible only inside the class that declares them. Members without a modifier are private.
  • protected members are visible inside the class and its subclasses.
  • public members are visible to Apex code in the same namespace.
  • global members are visible to all Apex code, including code in other namespaces, such as an installed managed package.

A small example

public class Counter {
    private Integer total = 0;

    public void add(Integer amount) {
        total += amount;
    }

    public Integer getTotal() {
        return total;
    }
}

Other classes cannot change total directly. They have to call add, which keeps the rule in one place. This is the same idea as Encapsulation in C++, applied to Apex.

Why global needs care

Other code may depend on a global member, so changing or removing one can break code outside your own namespace. Prefer public unless a managed package has to expose the member.

with sharing is not an access modifier

You will see with sharing and without sharing on class declarations, such as public with sharing class Counter. They control whether the class respects the running user’s record sharing rules. They do not decide which code can call the class’s members.

Comparing with C++ and Java

private, protected and public in Apex follow the same ideas as in Access Modifiers in C++. Apex’s default for members without a modifier is private, while Java’s default is package-level access, covered in What Are Access Modifiers in Java? C++ and Java have no direct equivalent of global, which is specific to Apex’s namespace model.

The complete guide to access modifiers

Access Modifiers in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

How to Use goto in C++

Learn how to use goto in C++: write a label and jump to it, see forward and backward examples, avoid compile errors, and pick safer alternatives.

goto 5 min read

The inline Keyword in C++

Learn how the inline keyword in C++ works, why inline functions belong in header files, how inline variables work in C++17, and when the compiler ignores it.

inline 3 min read