Object Oriented Programming in Salesforce Apex

Apex is an object-oriented programming language developed by Salesforce for building custom logic and automation. It is similar to Java and integrates with Salesforce’s database (SOQL, DML) to handle server-side logic.

Here, I will explain the concept of object-oriented programming in Salesforce Apex, along with related concepts and examples in Apex.

  • What is object-oriented programming in Salesforce Apex?
  • Classes and Objects in Salesforce Apex.
  • Encapsulation in Salesforce Apex.
  • Inheritance in Salesforce Apex.
  • Polymorphism in Salesforce Apex
  • Abstraction in Salesforce Apex.

What is Object-Oriented Programming in Salesforce Apex?

The object-oriented programming concept in Salesforce Apex refers to the practice of organizing code into objects, which serve as blueprints for creating instances of data. It is a method of programming that uses ‘objects’ to create applications and computer programs.

OOPs concepts in Apex include classes, objects, inheritance, encapsulation, and polymorphism, which help in creating modular, reusable, and maintainable code.

Understanding OOPs Concept in Salesforce Apex

Below, I have explained all the concepts included in object-oriented programming in Salesforce Apex.

1. Classes and Objects in Salesforce Apex

An Apex Class in Salesforce is a blueprint of an object (instance). Classes define what information an object will hold and what it can do, such as its structure (properties) and methods, for Salesforce objects.

Syntax: Creating an Apex Class –

public class class_Name {
      public void method_Name() {
         //Enter your logcic;
    }
}

The Object is an instance of a class, like a container that holds information such as absolute values instead of variables.

Syntax: Creating an Apex Class Object –

class_Name obj = new class_Name();

Here, I created a class with a public access modifier. Then, I declared a string and a parameterized constructor with the parameter as a string. Using this keyword, I assigned a name to the accountName and then displayed the variable using the debug method in the printAccountName() method.

public class Demo {
    public String accountName; 
    public Demo (String name) { 
        this.accountName = name;
      }
    public void printAccountName() {
        System.debug ( 'Entered Name : ' +accountName );
      }
}
Object Oriented Programming in Salesforce Apex

In the anonymous window, create an instance of a class using the new keyword, provide the string as accountName, and call the method. <