Salesforce is a popular CRM platform that companies use to optimize their operations and boost productivity. It unifies data, AI agents, apps, and metadata in one place to help businesses simplify interactions and drive customer success.
Apex is a strongly typed, object-oriented programming (OOP) language in Salesforce used to add business logic to system events.
This Salesforce Apex tutorial covers the language and how to use its commands efficiently with examples.
Table of Contents:
Let’s start by learning Apex classes in Salesforce.
Like Java, Apex also uses classes to perform tasks. A class is a model for creating objects, which are instances of the class.
For example, if we take a class called ‘Student’, it represents all the details of a student. An instance of the 'Student' class can include an ID and a student's name.
A class has variables that define an object's state and methods that define its behavior.
Declaring a Class in Apex:
Classes can be inner or outer. To declare a class, specify:
Classes can include implementations or extensions if needed.
Example:
private class viswaouterclass{
Statement1
Class mindinnerclass
{
Statement2
}
}
Apex Objects:
An object is an instance of a class. In Salesforce, objects can invoke class methods.
The code below shows how to create an object.
Public class MindMajix
Integer i=1000;
MindMajix objec1 = new MindMajix();
objec1.umethod(1000);
Access Modifiers in Apex:
The following access modifiers are available in Apex Programming.
Variable Declaration in an Apex Class:
To declare a variable in an Apex class, you must define the following:
The syntax for declaring a variable:
Private | Public | Protected | [static] [final] [global] data_type variable_name = value;
Example:
public global Boolean e = True;
Methods in Apex Class:
To declare a method in an Apex class, you must mention the following elements:
Syntax:
Protected | Private | Public | [override] [static] [global] data_type method_name(parameters)
{
Statements;
}
Example
private global float add( )
{
return e;
}
In real-world Salesforce development, understanding how these classes are applied in applications is crucial, and many professionals build this expertise through Salesforce developer training programs.
Constructor:
A constructor is called when an object is created. If a class does not have a customized constructor, it can use a default constructor.
The syntax for declaring a constructor is identical to that of a method. You should use the ‘new’ keyword to create an object, along with the constructor.
There are two types of constructors:
You can create a new object using a constructor as follows:
NewObject object1 = new NewObject()
Constructor Overloading:
If a class has multiple constructors with different argument lists, this is known as constructor overloading.
Apex Properties:
An Apex property is identical to a variable. Apex allows developers to use Apex properties to verify data before making modifications.
An Apex property can have the following:
Example:
private class BaseProperty
{
public Boolean prop1{
get {return prop1; }
set { prop1 = value; }
}
}
Apex Functions:
Apex allows you to use Apex functions to alter data by performing calculations, creating records, or assigning values to Visualforce properties. You can use functions in a Visualforce expression.
You can use the following functions in the Visualforce pages, as follows:
Extending a class:
A class can extend another class; this is called inheritance. For extending a class, Apex allows you to use the ‘extends’ keyword. The class that extends another class will use all the properties and methods of that class.
Override virtual methods of the extended class in derived classes using the ‘override’ keyword.
Example:
private Virtual Class Header {
private virtual void read() {
System.debug(' Read some content');
private virtual float average {
read 98.5;
}
}
When to make a method abstract?
When we cannot decide on the implementation and need to carry it out later, we make it abstract.
Example:
Public virtual class parent {
Private integer pvt_mem;
Protected integer ptd_mem;
Public integer pub_mem;
Public virtual void gets values (){
System. Debug ('Pvt Mem' +pvt_mem);
System.debug('ptd Mem' +ptd_mem);
System. Debug ('pub mem'+ pub_mem);
}
}
Public class child extends parent {
Private integer pvt_ch_mem
Public override void get values () {
System. Debug ('Pvt ch Mem' + pvt_ch_mem);
}
}
Global class test {
Public static test method void main () {
Parent p1= new parent ();
P2.get values ();
Child c1= new child(); c1.gets values ();
}
In summary, you can use Salesforce Apex classes to implement the actions associated with an object. Apex classes will have specific methods to perform the object's actions.
In this part of the Salesforce Apex tutorial, we’ll explore the OOPs concepts in Salesforce, including classes, inheritance, and overriding.
Classes:
There are two types of classes:
1. Static method: You can use a static method independently of an object, whereas you can use a non-static method with respect to the object.
You can access a static method using the command below.
ClassName.MethodName (parameters);
2. Non-static Method: A non-static method in an apex class belongs to an instance of the class. This method is declared without using the static keyword.
Example:
public class ContactManager {
private String instanceMessage = 'Hello from the instance!';
public List<Contact> getContactsByAccount(Id accountId) {
System.debug(instanceMessage);
return [SELECT Id, FirstName, LastName FROM Contact WHERE AccountId = :accountId];
}
public void setMessage(String msg) {
this. instanceMessage = msg; // 'this' refers to the current instance
}
}
The types of methods that you can perform using Apex are:
Inheritance:
Inheritance enables faster development of new features by allowing the reuse and modification of existing ones. The main advantage is the reusability of features.
You need at least two classes to work with inheritance, but all previous features are explored through a single class. Of these two classes, the one that contains essential features and provides members to another class is called the parent (or) base (or) superclass.
The class that reuses the existing class members or depends on the other class for its existence is known as a child (or) derived class (or) subclass.
Class parent{
}
Class child extends parent{
}
The following are the types of classes used in an inheritance
Overriding:
If a parent method is sufficient for a child, it cannot be overridden. Otherwise, it can be overridden in the child class.
In Apex, you can enable a child class to provide different implementations for a method that is already implemented in its parent class.
Note that the parent object doesn’t handle the child when it comes to an abstract class in Salesforce Apex.
A context variable is a special variable in Salesforce. You can get information about a trigger from this variable.
The following are some trigger context variables. All triggers define implicit variables. Developers can access the run-time context using these variables.
You can find these variables in the System.Trigger class.
| Variable | How it works |
| isExecuting | This variable returns true if the current context for the Apex code is a trigger |
| isInsert | It returns true if this trigger was fired because of an insert operation |
| isUpdate | It returns true if this trigger was fired because of an update operation |
| isDelete | It returns true if this trigger was fired because of a delete operation |
| isUndelete | It returns true if this trigger was fired after a record is recovered from the recycle bin. |
Example:
Trigger PropertyDiscountTrigger on Property_c (Before Insert){
RowHouseDiscount.applyDiscount(Trigger.new);
}
The Trigger.new variable that you see in the above code is a default one. After the trigger is activated, it loads all the records. You cannot modify this function. New is called a context variable, which is of type list.
Below is the sample code for using the ‘isExecuting’ variable.
---Code---
---Code ---
if(Trigger.isExecuting == True){
--- Code ---
}
---Code---
---Code---
---Code---
Below is the sample Code for using the ‘isInsert’ variable.
Program Logic#1:
---Code---
---Code ---
if(Trigger.isInsert == True){
--- Code ---
}
---Code---
---Code---
---Code---
Below is the sample Code for using the ‘isUpdate’ variable.
--- Code ---
--- Code ---
--- Code ---
if(Trigger.isUpdate == True && Trigger.isAfter == True ){
--- Code to work only before insert is done ----
--- Not for update, not for insert-----------------
}
--- Code ---
--- Code --
--- Code ---
Now that you have understood Salesforce context variables with clear examples.
Let’s learn how annotations work in Salesforce in this Apex Salesforce tutorial.
Example:
global class My Class {
@ future
Public static void my Method (string a)
{
// long - running Apex code
}
}
You can use the deprecated annotation to mark methods, classes, exceptions, enums, interfaces, or variables as deprecated. The key point is that these methods or other elements should no longer be referenced in subsequent releases of the managed package.
This annotation is useful when refactoring code in package management.
Let’s explore more about the deprecated annotation in Salesforce.
Public void my method (string a) { }?
Apex allows you to use the @future annotation to identify a method that executes asynchronously. When you specify the @future annotation, the method executes when Salesforce has available resources.
Methods with future annotation must be static. They can only return void. You can define a method with the @future annotation to make it execute asynchronously.
You can use the future annotation when making an asynchronous web service callout to an external service.
Without the annotation, the web service callout is made on the same thread that executes the Apex code, and no additional processing can happen until the callout completes (synchronous processing).
Example:
global class My future class {
@ future
static void My method (string a, integer i) {
System. Debug ('Method called with: '+a+' and '+i);
// do callout
}
}
You can use the code below to specify if a method executes a callout:
@ future (callout = true )
public static void do callout from future ()
{
// Add code to perform callout
}
You can specify (callout = false) to prevent a method from making callouts.
You can use the @isTest annotation to define classes and individual methods that only contain code used for testing your application. This annotation is similar to declaring a method as a test method.
Classes and methods defined as @isTest can be either private or public. Classes defined with @isTest must be top-level classes.
Example:
@ isTest
Private class My Class {
@ isTest static void test 1 () {
}
@ isTest static void test 2 () {
}
}
Example:
A Public test class that contains utility methods for test data creation:
@ isTest
public class TestUtil {
public static void create Test Accounts () {
}
public static void create Test Contacts () {
}
This annotation enables unrestricted queries on the Salesforce database. This annotation prevents you from performing the following operations in the request while removing the limit on the number of rows returned.
The @ReadOnly annotation is available for web services and the schedulable interface. The top-level request must be scheduled for execution, or use the Web service invocation to use the @ReadOnly annotation.
Example:
If a Visualforce page calls a web service that contains the @ReadOnly annotation, the request fails because Visualforce is the top-level request, not the web service.
Visualforce pages can call controller methods annotated with @ReadOnly, and these methods will run with relaxed restrictions.
To increase other Visualforce-specific limits, you must set the Read-Only attribute on the tag to true.
This annotation provides support for Apex methods used in Visualforce. This process is often referred to as JavaScript remoting. Moreover, methods annotated with @RemoteAction must be both global and static.
You add the request as a JavaScript invocation to use JavaScript remoting in a Visualforce page, which must take the following form.
[]. (
[params .... , ]
<(Call back function>(result, event) {
// callback function logic
}, {escape: true});
The callback function is the JavaScript function that handles the controller's response and receives the method call status and the returned result as parameters.
Escape specifies whether your Apex methods require the response to be escaped (by default, true) or not (false).
In your controller, your Apex method declaration is processed with the @RemoteAction annotation like this.
@remote action
Global static string gets an item ID (string, object name) ( .... )
Now that you understand the different types of annotations used in Salesforce Apex, with suitable examples.
Ans: Not at all. You can learn Salesforce Apex easily. Salesforce Apex is a simple programming language that anyone can learn quickly, even with little technical background.
Ans: You can learn Salesforce Apex in 3 – 4 weeks. You need to work on more hands-on exercises to become a skilled Salesforce Apex developer. MindMajix offers advanced Salesforce Apex developer training for beginners and experienced learners alike.
Ans:
Ans: If its implementation is complete and requires no modification, use it as the final version.
Ans: A method is implemented for a specific purpose and can be modified for any other purpose.
Mastering Apex is essential for building scalable, robust Salesforce applications. We hope this Salesforce Apex tutorial has equipped you with core Apex concepts along with practical examples.
If you are interested in learning more about Salesforce Apex, you can register for a Salesforce developer course from MindMajix. By the end of the training, you will gain strong skills in Salesforce Apex and Lightning and advance your career in the Salesforce domain.

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
| Name | Dates | |
|---|---|---|
| Salesforce Training | May 12 to May 27 | View Details |
| Salesforce Training | May 16 to May 31 | View Details |
| Salesforce Training | May 19 to Jun 03 | View Details |
| Salesforce Training | May 23 to Jun 07 | View Details |