Salesforce Apex Tutorial

(4.8)
1564 Viewers

This Salesforce Apex tutorial provides a practical understanding of the Apex language, with examples. In this tutorial, you will explore Apex concepts, syntax, and real-world use cases in detail. By the end of this short guide, you will gain the skills to write efficient Apex code and develop robust Salesforce applications.

Salesforce Apex Tutorial
  • Blog Author:
    Kalla SaiKumar
  • Last Updated:
    08 May 2026
  • Views:
    1564
  • Read Time:
    30:47 Minutes
  • Share:
Salesforce Articles

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:

Apex Classes in Salesforce:

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:

  • Access Modifier – You should use any modifier (public, protected, private) for the top-level class or inner class.
  • Modifier – If required, you can specify modifiers such as abstract or virtual.
  • ‘Class’ Keyword – You should declare this keyword before the name of the class.

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.

  • Public: Anyone in the program or namespace can use a public method.
  • Private: This is the Default Access Modifier. Private methods are accessible only to the Apex class in which they are declared.
  • Protected: The protected method can be used by the inner class in which it is declared and the outer classes that extend that inner class.
  • Global: Global methods are available to all classes that use the class in which they are declared.

Variable Declaration in an Apex Class:

To declare a variable in an Apex class, you must define the following:

  • Access Modifiers – If you want to specify an access modifier for a variable, you must do so before the variable.
  • Data Type – Every variable needs a type, like Integer or Boolean.
  • Name – Each variable needs a name.
  • Value – Assign a value, if needed

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:

  • Modifier: Use modifiers such as protected or public as needed.
  • Data Type: Since the method returns specific values, you should specify the data type for those values. If the method does not return a value, use the ‘void’ data type.
  • Parameters: Methods can have parameters or empty parentheses.
  • Statements: The statements or code associated with a method should be contained in the braces '{}'.

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:

  • Constructor with no arguments (Default Constructor)
  • Constructor with argument

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:

  • Access modifier: You can apply all the Access Modifiers to a property.
  • Return type: Every Property will have a return_type, such as Boolean, Integer, etc.
  • Property name: Every property should have a name.

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:

  • ADDMONTHS: It yields the date that refers to the number of months after or before a particular date.
  • DATEVALUE: It yields a date value from time/date or an expression under test.
  • DATETIMEVALUE: It yields month, day, year, and GMT.
  • DAY: It yields the day of the month as a number between 1 and 31.

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.

MindMajix YouTube Channel

Classes, Inheritance, and Overriding in Salesforce

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
  2. Non-Static method

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:

  1. Constructors → [DC, PC]
  2. Setters
  3. Getters
  4. Operations (actions) → in Apex

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.

  • Syntax for Inheritance:
Class parent{
}
Class child extends parent{
}

The following are the types of classes used in an inheritance

  • Final
  • Virtual
  • Abstract

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.

  • This is possible only through inheritance.
  • Multiple methods with the same name can be inherited (virtual) or overridden in a child class.

Note that the parent object doesn’t handle the child when it comes to an abstract class in Salesforce Apex.

Context Variables in Salesforce:

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.

VariableHow it works
isExecutingThis variable returns true if the current context for the Apex code is a trigger
isInsertIt returns true if this trigger was fired because of an insert operation
isUpdateIt returns true if this trigger was fired because of an update operation
isDeleteIt returns true if this trigger was fired because of a delete operation
isUndeleteIt 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.

Annotation in Salesforce:

Let’s learn how annotations work in Salesforce in this Apex Salesforce tutorial.

  • Apex allows developers to use annotations to give additional information to the compiler at runtime.
  • An Apex annotation modifies the way a method or class is used.
  • You can define annotations with an initial @symbol, followed by the appropriate keyword.
  • If you want to add an annotation to a method, you must specify it immediately before the method or class definition.

Example: 

global class My Class {
@ future
Public static void my Method (string a)
{
// long - running Apex code
}
}
  • Deprecated Annotation:

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.

    • New subscribers cannot see the deprecated elements, while existing subscribers and API integrations continue to function.

      Example: @deprecated
      Public void my method (string a) { }?
    • Unmanaged packages cannot contain code that uses the deprecated keyword.
    • When a custom object is deprecated, all global access that modifies the reference to the deprecated identifier must also be deprecated.
    • Any global method that uses the deprecated type in its signature must also be deprecated.
    • A deprecated item, such as a method or a class, can still be referenced internally by the package developer.
    • You cannot deprecate Web service methods and variables.
    • You can’t remove the deprecated annotation to remove the deprecated status in Apex after you’ve released a package version where that item in Apex is deprecated.
    • You can deprecate an enum, but you cannot deprecate individual enum values.

 

  • Future Annotation:

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.

 

  • @IsTest Annotation

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 () {
}

 

  • @ReadOnly Annotation:

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.

    • DML operations
    • Calls to the System.schedule
    • Calls to methods annotated with @future
    • Sending emails

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.

 

  • @RemoteAction Annotation

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 namespace is your organization’s name; this is required only if the class comes from an installed package.
  • The Controller is the name of your Apex controller.
  • The method is the name of the Apex method you are calling.
  • Params is a comma-separated list of parameters that your method accepts.

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.

Frequently Asked Questions:

1. Is it hard to learn Salesforce Apex?

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.

2. How long will it take to learn Salesforce Apex?

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.

3. Can I get learning resources on Salesforce?

Ans: 

4. When to make a method final?

Ans: If its implementation is complete and requires no modification, use it as the final version.

5. When to make a method virtual?

Ans: A method is implemented for a specific purpose and can be modified for any other purpose.

Conclusion:

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.

 

logoOn-Job Support Service

Online Work Support for your on-job roles.

jobservice
@Learner@SME

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:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreContact us
Course Schedule
NameDates
Salesforce TrainingMay 12 to May 27View Details
Salesforce TrainingMay 16 to May 31View Details
Salesforce TrainingMay 19 to Jun 03View Details
Salesforce TrainingMay 23 to Jun 07View Details
Last updated: 08 May 2026
About Author

Kalla Saikumar is a technology expert and is currently working as a Marketing Analyst at MindMajix. Write articles on multiple platforms such as Tableau, PowerBi, Business Analysis, SQL Server, MySQL, Oracle, and other courses. And you can join him on LinkedIn and Twitter.

read less