Apex Classes and Methods
Apex Classes and Methods are fundamental building blocks of business logic in Salesforce development. Apex is a strongly-typed, object-oriented programming language that runs on the Salesforce platform, and understanding classes and methods is essential for the Platform Developer I certification. … Apex Classes and Methods are fundamental building blocks of business logic in Salesforce development. Apex is a strongly-typed, object-oriented programming language that runs on the Salesforce platform, and understanding classes and methods is essential for the Platform Developer I certification. **Apex Classes** are blueprints or templates that define the properties (variables) and behaviors (methods) of objects. They encapsulate related logic and data together. Classes can include access modifiers such as `public`, `private`, `global`, and `virtual` to control visibility and inheritance. A class can implement interfaces, extend other classes, and contain inner classes. Example: ``` public class AccountHandler { private String accountName; public AccountHandler(String name) { this.accountName = name; } } ``` **Methods** are functions defined within a class that perform specific operations. They can accept parameters, return values, and be declared as `static` (called on the class itself) or instance-based (called on an object). Methods also support access modifiers to control their accessibility. Key method types include: - **Static methods**: Invoked without instantiating the class (e.g., `AccountHandler.getAccounts()`) - **Instance methods**: Require object creation before invocation - **Constructors**: Special methods called during object instantiation **Important Concepts for the Exam:** 1. **Governor Limits**: Apex operates under strict execution limits (e.g., SOQL queries, DML statements) to ensure shared resource efficiency. 2. **Bulk Processing**: Methods should handle collections of records rather than single records to optimize performance. 3. **Trigger Context**: Apex classes are commonly invoked from triggers to separate business logic from trigger definitions (best practice). 4. **Test Classes**: Every Apex class requires at least 75% code coverage through test methods annotated with `@isTest`. 5. **Sharing Rules**: Classes can be declared with `with sharing` or `without sharing` to enforce or bypass record-level security. Mastering Apex classes and methods is critical for building scalable, maintainable automation solutions on the Salesforce platform.
Apex Classes and Methods – Salesforce Platform Developer 1 Exam Guide
Why Apex Classes and Methods Matter
Apex is the strongly-typed, object-oriented programming language used on the Salesforce platform. Classes and methods form the fundamental building blocks of all Apex code. Whether you are writing triggers, batch jobs, web services, or custom controllers, you will always work within the structure of Apex classes and methods. For the Salesforce Platform Developer 1 (PD1) exam, Process Automation and Logic is one of the most heavily weighted sections, and a solid understanding of Apex classes and methods is essential to passing.
What Are Apex Classes?
An Apex class is a blueprint or template that defines a set of properties (variables) and behaviors (methods). Just like classes in Java or C#, Apex classes support:
• Encapsulation – bundling data and methods that operate on that data within a single unit.
• Inheritance – a class can extend another class using the extends keyword. Apex supports single inheritance only.
• Interfaces – a class can implement one or more interfaces using the implements keyword. Interfaces define method signatures without implementations.
• Abstract classes – declared with the abstract keyword; they can contain both abstract methods (no body) and concrete methods (with a body). They cannot be instantiated directly.
• Virtual classes – declared with the virtual keyword; they allow methods to be overridden by subclasses using the override keyword.
A basic Apex class looks like this:
public class AccountService {
private String accountName;
public AccountService(String name) {
this.accountName = name;
}
public String getAccountName() {
return accountName;
}
}
Access Modifiers
Apex supports several access modifiers that control the visibility of classes and methods:
• public – The class or method is accessible from anywhere within the same namespace.
• private – The class or method is accessible only within the class where it is defined. Inner classes can be private. Top-level classes cannot be private.
• protected – The method or property is accessible within the class and by any subclasses that extend it.
• global – The class or method is accessible across all namespaces. Required for web services, REST/SOAP APIs, and managed packages that expose functionality externally.
Key exam point: The default access modifier for a method is private. Top-level classes must be declared as either public or global.
What Are Apex Methods?
Methods are blocks of code within a class that perform specific operations. They have a return type, a name, and optional parameters.
public static List<Account> getActiveAccounts() {
return [SELECT Id, Name FROM Account WHERE Active__c = 'Yes'];
}
Key Method Concepts:
• Instance methods – Belong to a specific instance of a class. You must create an object using the new keyword before calling them.
• Static methods – Belong to the class itself, not to an instance. They are called using the class name (e.g., AccountService.getActiveAccounts()). Static methods cannot access instance variables or instance methods directly.
• Constructors – Special methods that share the same name as the class and have no return type. They are invoked when you instantiate a class with the new keyword. If no constructor is defined, Apex provides a default no-argument constructor.
• Method overloading – You can define multiple methods with the same name but different parameter lists (different number or types of parameters).
• Return types – Methods must declare a return type. Use void if the method does not return anything.
How Classes and Methods Work Together
1. Define a class with appropriate access modifiers and keywords (virtual, abstract, with sharing, etc.).
2. Define member variables to hold data.
3. Define constructors for initialization logic.
4. Define methods to perform business logic, DML operations, SOQL queries, callouts, etc.
5. Instantiate the class (for instance methods) or call static methods directly.
Important Keywords and Concepts
• with sharing / without sharing – Controls whether the class enforces the current user's sharing rules. with sharing enforces them; without sharing does not. If neither is specified, the class runs in the sharing context of the calling class. Exam favorite!
• inherited sharing – The class inherits the sharing mode of the class that called it. Useful for utility classes. Available in API version 43.0 and later.
• static variables – Persist for the duration of a single transaction. They are commonly used to prevent recursive trigger execution.
• final keyword – When applied to a variable, it becomes a constant that can only be assigned once.
• this keyword – Refers to the current instance of the class.
Inner Classes
Apex supports inner (nested) classes. Key rules:
• An inner class can be declared as public, private, or global.
• Inner classes can have their own methods and constructors.
• An inner class does not have access to the instance variables of the outer class; it behaves like a static context.
• You can nest classes only one level deep (no inner class within an inner class).
Interfaces
Interfaces define a contract that implementing classes must follow.
public interface Discountable {
Decimal calculateDiscount(Decimal amount);
}
public class VIPDiscount implements Discountable {
public Decimal calculateDiscount(Decimal amount) {
return amount * 0.20;
}
}
Common Salesforce interfaces you should know for the exam:
• Database.Batchable – for batch Apex
• Schedulable – for scheduled Apex
• Queueable – for queueable Apex
• Comparable – for custom sorting
• HttpCalloutMock / WebServiceMock – for testing callouts
Abstract Classes vs. Interfaces
• Abstract classes can have both implemented and unimplemented methods; interfaces only have unimplemented method signatures.
• A class can implement multiple interfaces but can extend only one abstract (or virtual) class.
• Abstract classes can have member variables with values; interfaces cannot.
Properties
Apex supports properties with getter and setter accessors:
public String name { get; set; }
You can also define custom logic in getters and setters:
public String name {
get { return name; }
set { name = value.toUpperCase(); }
}
Testing Apex Classes and Methods
• Test classes are annotated with @isTest and do not count against the org's Apex code limit.
• Test methods must be static, return void, and take no parameters.
• Use System.assert(), System.assertEquals(), and System.assertNotEquals() to verify expected outcomes.
• Salesforce requires at least 75% code coverage across the org for deployment, but aim for 90%+ and meaningful assertions.
• Test data is isolated by default (API v24.0+). Use @TestSetup methods to create reusable test data for the test class.
• Use Test.startTest() and Test.stopTest() to reset governor limits within a test and to execute asynchronous code synchronously.
Governor Limits Awareness
When writing Apex classes and methods, always be mindful of governor limits:
• 100 SOQL queries per synchronous transaction
• 150 DML statements per transaction
• 10-second CPU time limit (synchronous)
• Heap size limit of 6 MB (synchronous) / 12 MB (asynchronous)
Bulkify your code: never place SOQL queries or DML statements inside loops.
Common Exam Scenarios
1. Identifying correct access modifiers – e.g., what happens if a method is private? Can it be called from another class?
2. Static vs. instance context – Can a static method call an instance variable directly? (No.)
3. with sharing behavior – Which records does a user see when a class is declared with sharing vs. without sharing?
4. Constructor chaining – Using this() to call another constructor within the same class.
5. Method overloading – Recognizing valid overloaded method signatures.
6. Interface implementation – Ensuring all methods defined in an interface are implemented in the class.
7. Testing patterns – Choosing the right assertions and understanding test data isolation.
Exam Tips: Answering Questions on Apex Classes and Methods
1. Read every answer choice carefully. Exam questions often include distractors that differ by a single keyword (e.g., virtual vs. abstract, public vs. global). Pay close attention to these distinctions.
2. Know the rules about static vs. instance. This is a recurring theme. Remember: static methods and variables belong to the class, not an instance. Static methods cannot reference this or instance members without creating an object first.
3. Memorize access modifier rules. Top-level classes can only be public or global. Inner classes can also be private. Methods default to private if no modifier is specified. global methods must be in a global class.
4. Understand sharing keywords deeply. Questions may describe a scenario where a user cannot see certain records and ask you to fix the class declaration. Know that with sharing enforces sharing rules, without sharing bypasses them, and inherited sharing inherits from the caller.
5. Look for compile-time errors. Many questions present code snippets and ask if the code compiles. Watch for: methods not implemented from an interface, calling instance methods from a static context, using override without the parent method being virtual or abstract, and missing return statements.
6. Know the difference between abstract classes and interfaces. If a question asks which approach allows partial implementation, the answer is an abstract class. If it asks which approach allows a class to conform to multiple contracts, the answer is interfaces.
7. Practice constructor scenarios. Know that if you define a parameterized constructor, the default no-argument constructor is no longer available unless you explicitly define it.
8. Be comfortable with test class rules. Test methods cannot be used to call web services (use mocks instead). Test classes annotated with @isTest cannot be instantiated in production code. Understand when to use SeeAllData=true (generally avoid it, but know it exists).
9. Bulkification is always relevant. If a question shows SOQL or DML inside a for-loop, that is almost always the wrong answer. Choose the option that collects data in a list and performs DML outside the loop.
10. Eliminate obviously wrong answers first. In many PD1 questions, one or two options can be ruled out quickly based on fundamental rules (e.g., a private top-level class, or a static method accessing this). Narrowing down to two options makes it much easier to select the correct one.
11. Practice with code. The best way to prepare is to write Apex classes in a Developer Edition org or Trailhead Playground. Hands-on experience with compilation errors and runtime behavior builds the intuition you need during the exam.
By mastering Apex classes and methods — their structure, access controls, inheritance model, and testing requirements — you will be well-prepared to handle a significant portion of the Platform Developer 1 exam confidently.
🎓 Unlock Premium Access
Salesforce Certified Platform Developer I + ALL Certifications
- 🎓 Access to ALL Certifications: Study for any certification on our platform with one subscription
- 2750 Superior-grade Salesforce Certified Platform Developer I practice questions
- Unlimited practice tests across all certifications
- Detailed explanations for every question
- PD1: 5 full exams plus all other certification exams
- 100% Satisfaction Guaranteed: Full refund if unsatisfied
- Risk-Free: 7-day free trial with all premium features!