Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท Classes and Testing

Apex Classes, Interfaces and Access Modifiers

Learn how Apex classes, constructors, interfaces, access modifiers and sharing keywords work, with real Apex code and runnable Java stand-ins for the design ideas.

Everything you write in Apex lives in a class. Triggers stay thin and hand their work to classes, tests are classes, batch jobs are classes, and even your REST endpoints are classes with annotations. If you learn to design Apex classes well, most of the rest of the platform becomes easier. This lesson covers the building blocks: fields, methods, constructors, access modifiers, the sharing keywords that are unique to Salesforce, and interfaces.

Apex only runs inside a Salesforce org, and this site cannot run an org. The Apex listings below are read-only and we only show output where it is certain. The runnable examples are Java stand-ins: Java and Apex share the same object-oriented model, so the Java code lets you experiment with the design idea (an interface and two implementations, for example). Every stand-in is labelled. Where Apex differs from Java, we say so.

A first Apex class

An Apex class has a name, an access modifier, optional sharing behaviour, fields and methods. This one models a simple discount calculator:

APEX
public with sharing class DiscountCalculator {
    private final Decimal baseRate;

    public DiscountCalculator(Decimal baseRate) {
        this.baseRate = baseRate;
    }

    public Decimal priceAfterDiscount(Decimal listPrice, Integer quantity) {
        Decimal rate = baseRate;
        if (quantity >= 100) {
            rate = rate + 0.05;
        }
        return listPrice * (1 - rate);
    }
}

Use it from anonymous Apex or another class:

APEX
DiscountCalculator calc = new DiscountCalculator(0.10);
System.debug(calc.priceAfterDiscount(200, 150)); // 170.00

Notice a few Apex details. Types are Decimal, Integer, String, Boolean, Date and so on, not Java's double or int. System.debug writes to the debug log. Class names are case-insensitive, and the class must live in its own .cls file when you work with source-driven development (see Salesforce CLI and deployment).

Access modifiers

Apex has four access levels for members and top-level classes:

Modifier Who can use it
private Only the class that declares it (the default for members)
protected The class and its subclasses
public Any Apex in your namespace
global Any Apex, including other namespaces (managed packages)

A top-level class must be public or global; private is for inner classes and members. Use the narrowest level that works. If the class is not part of a managed package, you almost never need global.

Sharing keywords

This is the first place Apex differs sharply from Java. By default Apex runs in system mode: it can read and change records the current user could not see. The sharing keyword on a class decides whether record-level sharing rules are enforced:

  • with sharing enforces the sharing rules of the running user.
  • without sharing ignores them.
  • inherited sharing takes the mode of the caller (safe for utility classes).
  • If you write nothing, the class runs in the mode of the caller too, but entry points such as triggers and REST resources run without sharing, so always state your intent.

Sharing rules do not enforce field-level or object-level security. For those, use WITH USER_MODE in SOQL (see the SOQL lessons) or Schema describe checks. A good default for any class that touches data is with sharing; opt out only with a comment explaining why.

Constructors and static members

A constructor has the class name and no return type. You can overload constructors and call one from another with this(...). Static members belong to the class, not an instance. Static variables live for one transaction only, which makes them a handy place for a "have I already run?" flag in triggers (we use this in the trigger framework project).

APEX
public class RetryPolicy {
    public static final Integer MAX_ATTEMPTS = 3;
    private Integer attempts = 0;

    public RetryPolicy() { }

    public Boolean allowAnother() {
        attempts++;
        return attempts <= MAX_ATTEMPTS;
    }
}

Interfaces

An interface declares method signatures without bodies. Classes that implements it must provide every method. Interfaces let calling code depend on a capability instead of a concrete class, which makes code easy to test and extend.

APEX
public interface PriceStrategy {
    Decimal price(Decimal listPrice, Integer quantity);
}

public class StandardPrice implements PriceStrategy {
    public Decimal price(Decimal listPrice, Integer quantity) {
        return listPrice * quantity;
    }
}

public class VolumePrice implements PriceStrategy {
    public Decimal price(Decimal listPrice, Integer quantity) {
        Decimal total = listPrice * quantity;
        return quantity >= 100 ? total * 0.9 : total;
    }
}

Apex also ships standard interfaces you will meet soon: Database.Batchable, Queueable, Schedulable and Comparable (see Asynchronous Apex). Implement them and the platform calls your methods at the right time.

Try the idea: strategy interface (Java stand-in)

Java Stand-in: one interface, two implementations (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The quote method knows only the interface. In Apex you would write the same method with PriceStrategy strategy as the parameter, and a test could pass a fake strategy.

Try the idea: sharing as a flag (Java stand-in)

Record sharing is not something Java has, so this stand-in only shows the idea: the same query code returns different results depending on a mode flag.

Java Stand-in: sharing mode changes what a query returns (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common mistakes

  • Leaving out the sharing keyword and unknowingly exposing data when the class is called from a REST resource or trigger.
  • Making everything public or global. A global method can never be removed from a managed package.
  • Putting business logic in the trigger file instead of a class, which makes it hard to test. See Apex test classes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which sharing keyword makes a class respect the running user's record-level sharing rules?

    with sharing enforces the sharing rules of the current user. without sharing ignores them, and global and private are access modifiers, not sharing keywords.
  2. 2. What is the default access level of a member (field or method) with no modifier in Apex?

    Members default to private, so only the declaring class can use them.
  3. 3. Why prefer an interface parameter such as PriceStrategy over a concrete class?

    Depending on a capability instead of a class lets you swap implementations and substitute test doubles.
  4. 4. Which keyword is the safest choice for a utility class used from both user-facing and system code?

    inherited sharing uses the mode of the caller, so the utility never widens access on its own.

Summary

  • Apex code lives in classes; triggers, batches and tests are all classes.
  • Access levels are private, protected, public and global; choose the narrowest.
  • Sharing keywords (with, without, inherited) control record visibility, not field security.
  • Interfaces describe a capability; platform interfaces such as Queueable plug your code into the platform.
  • Stand-ins here are Java; the real Apex runs only in an org.

Next: Inheritance, Virtual Methods and Abstract Classes