
Methods in Salesforce Apex

Table of Contents
What is a method?
A method in programming is a block of code designed to perform a specific task, encapsulated within a class or object, which can be called and executed whenever needed, often with the ability to receive inputs (parameters) and return a result.
Here’s an example of a method in Salesforce Apex:
public class Calculator {
// Method to add two numbers
public Integer addNumbers(Integer num1, Integer num2) {
Integer sum = num1 + num2; // Add the numbers
return sum; // Return the result
}
}
// Calling the method
Calculator calc = new Calculator();
Integer result = calc.addNumbers(10, 20); // result will be 30
System.debug('Sum of numbers: ' + result);
In this example:
addNumbers
is a method that takes two integers as input (num1
andnum2
), adds them, and returns the sum.- We call this method by creating an instance of the
Calculator
class and using it to perform the addition task.
Read more: Data Loader Management in Salesforce
Access Modifier:
An access modifier is a keyword in programming languages that sets the accessibility or visibility of classes, methods, and other members. Access modifiers control where these members can be accessed from, enhancing security and encapsulation in code.
public class AccessModifierExample {
// Private variable - can only be accessed within this class
private String privateMessage = 'This is private';
// Public method - can be accessed by other classes in the same namespace
public String getPublicMessage() {
return 'This is public';
}
// Global method - can be accessed from any package, including managed packages
global String getGlobalMessage() {
return 'This is global';
}
// Protected method - can be accessed by this class and any class that extends this class
protected String getProtectedMessage() {
return 'This is protected';
}
// Private method - can only be accessed within this class
private String getPrivateMessage() {
return privateMessage;
}
// Public method to display all messages
public void showMessages() {
System.debug(getPublicMessage());
System.debug(getGlobalMessage());
System.debug(getProtectedMessage());
System.debug(getPrivateMessage()); // Accessing private method within the class
}
}
// Calling the public method from another class
public class AccessModifierTest {
public void displayMessages() {
AccessModifierExample example = new AccessModifierExample();
example.showMessages(); // This will display all messages
}
}
Explanation:
private
: TheprivateMessage
variable and thegetPrivateMessage()
method are only accessible within theAccessModifierExample
class.public
: ThegetPublicMessage()
method is accessible from other classes in the same namespace.global
: ThegetGlobalMessage()
method is accessible globally, even in managed packages.protected
: ThegetProtectedMessage()
method can be accessed within the class and by any subclasses that extend this class.
The showMessages()
method is used to display all the messages by calling each method, including the private one.
Read more: What are classes in Salesforce Apex?
Common Access Modifiers:
In Apex, there are four common access modifiers: public, private, protected, and global. The public modifier allows methods and variables to be accessed from any other class within the same namespace. For example, a method defined as public void myMethod()
can be accessed throughout the namespace.
public void myMethod() { }
The private modifier restricts access to within the class where the method or variable is declared. For instance, private void myMethod()
can only be accessed inside the same class and is hidden from other classes.
private void myMethod() { }
The protected modifier in Apex allows access within the class itself, its subclasses, and other classes within the same namespace. For example, protected void myMethod()
can be accessed in classes that inherit from the original class or are part of the same namespace.
protected void myMethod() { }
The global is an Apex-specific modifier, which allows methods and variables to be accessed by any Apex code in any namespace, including managed packages. For example, a global void myMethod()
can be accessed universally across all namespaces.
global void myMethod() { }
Read more:Â Workflow rules in Salesforce
Example:
public class ExampleClass {
private Integer myPrivateVariable; // Private access modifier
public Integer myPublicVariable; // Public access modifier
protected void myProtectedMethod() {
// Protected method logic
}
global void myGlobalMethod() {
// Global method logic
}
}
This code defines a class ExampleClass
with different access modifiers:
myPrivateVariable
: A private variable that can only be accessed within theExampleClass
.myPublicVariable
: A public variable accessible by any class in the same namespace.myProtectedMethod()
: A protected method that can be accessed by the class and its subclasses.myGlobalMethod()
: A global method that can be accessed by any class, even in other namespaces or managed packages.
Read more: Approval Process in Salesforce.
Data Type:
Data types specify the type of data a variable can hold, such as integers, strings, Booleans, etc.
Example:
public class MyDataTypes {
Integer myNumber = 10;
String myString = 'Hello, Salesforce!';
Boolean myBoolean = true;
}
Read more: Relationship Fields in Salesforce.
Input Parameters:
Input parameters are the variables passed to a method when it is called. They allow methods to receive data to process.
Example:
public class MyParameters {
public void myMethod(String name, Integer age) {
System.debug('Name: ' + name);
System.debug('Age: ' + age);
}
}
Read more: SOQL Query in Salesforce
Body of Method:
Method body enclosed in braces {}. All the method code is written here, including local variable declarations.
Syntax:
[public | private | protected | global] [override] [static] data_type method_name
(input parameters) {
// The body of the method
}
Checkout: DML statements in Salesforce
Example:
/**
*public access modifier
*void return type
*name parameter
*/
Public static void updateContact(string name){
//method body
List<Contact> conList = [Select Id,FirstName,LastName from Contact Where LastName =: name];
List<contact> listToUpdate = new List<Contact>();
for(contact con:conList){
con.Title = 'Manager';
listToUpdate.add(con);
}
CRS Info Solutions offers a comprehensive and dynamic Salesforce online course designed specifically for beginners looking to build a successful career in the Salesforce ecosystem. Our program covers all the essential skills required to excel in Salesforce, including administration, development, and Lightning Web Components (LWC). By focusing on these critical areas, we ensure that learners are well-equipped to manage Salesforce platforms, develop custom solutions, and create modern, user-friendly interfaces using LWC. Whether you’re new to Salesforce or looking to strengthen your foundational skills, our course provides the perfect learning environment to get started.
In addition to teaching technical concepts, we provide essential Salesforce interview questions and thorough certification preparation to ensure students are ready for real-world challenges. Our course includes daily notes, real-world examples, and continuous support to help beginners grasp key topics efficiently. We also understand how important interview readiness is for landing a job, so we offer strategic job preparation guidance throughout the course. With hands-on experience, mock interview sessions, and insights into the types of questions asked in Salesforce interviews, we help students build their confidence and be well-prepared for the job market.
Furthermore, our Salesforce online course is tailored for thorough certification preparation, ensuring that beginners are equipped to tackle Salesforce certification exams with ease. We offer step-by-step guidance on the certification process, helping learners focus on key exam topics while gaining practical knowledge through our course. By the end of the program, students will not only have the skills required to pass their certification exams but will also be strategically prepared to secure job opportunities in the competitive Salesforce ecosystem.