OOPs Concept in Salesforce Apex with Examples

Salesforce Apex is a powerful tool for building flexible solutions within Salesforce. It uses Object-Oriented Programming (OOP) concepts, which are like building blocks for developers. Understanding these concepts is really important for developers to make the most out of Salesforce.

OOP in Apex includes ideas like encapsulation, inheritance, and polymorphism. These are fancy words, but they basically mean that developers can create code that’s easy to reuse and change. It’s like building with Lego bricks – you can put them together in different ways to make lots of different things!

By using OOP in Apex, developers can make their code more organized, easier to understand, and simpler to update. This helps them create better solutions for businesses using Salesforce.

What is salesforce apex OOPs Concept?

Object-Oriented Programming (OOPs) concepts in Salesforce Apex refer to the principles of organizing code around objects, which are like blueprints for creating instances of data. OOPs concepts in Apex include classes, objects, inheritance, encapsulation, and polymorphism, which help in creating modular, reusable, and maintainable code.

Understanding Object-Oriented Concepts in Salesforce Apex:

In the world of Salesforce Apex programming, it’s important to know about object-oriented concepts. Object-Oriented Programming (OOPs) in Salesforce Apex isn’t just a bunch of rules; it’s a powerful way of thinking that guides how we design and create things in Salesforce Apex.

Exploring OOPs in Salesforce Apex: So, what exactly is OOPs in Salesforce Apex? Let’s break it down and understand it through the main ideas of Salesforce Apex.

Objects:

In Salesforce Apex, think of an object like a container that holds information. For example, if you’re dealing with cars, you’d have an object for each car that stores details like its color, brand, and speed. These objects are like digital versions of real-world things and can also do stuff like speeding up or stopping.

Classes:

Classes in Salesforce Apex are like blueprints for making objects. They define what information an object will hold and what it can do. So, if you have a blueprint for a car, it will list things like color and methods for actions like speeding up.

Abstraction:

Abstraction is about simplifying things. In Salesforce Apex, it means focusing on what something does, rather than how it does it. So, instead of worrying about how a car moves, we just care that it can move. We leave the details for later.

Inheritance:

Inheritance is like passing down traits in a family. In Salesforce Apex, it means a new class can inherit characteristics from an existing class. For instance, an electric car can inherit traits from a regular car, like having wheels and doors.

Polymorphism:

Polymorphism is about having different forms. In Salesforce Apex, it means methods or objects can do different things in different situations. For example, a method to draw shapes might draw circles differently than squares.

Encapsulation:

Encapsulation is like putting things in a box. In Salesforce Apex, it means bundling data and methods together and protecting them. So, you can’t mess with a car’s speed directly you have to use methods like accelerate or brake. This helps keep things organized and safe.

Salesforce Apex is really good at following the principles of OOP. It’s important to understand these principles because they help us write code that works well and is easy to change. Knowing how OOP works in Salesforce Apex is key for making programs that are efficient and easy to work with. These concepts are the building blocks of modern software development on the Salesforce platform. They let developers create programs that are smart and can grow with the needs of the business.

OOPs Concepts in Salesforce Apex with Examples:

  • Class Example: class Car { String color; void accelerate(){...}}
  • Object Example: Car myCar = new Car();
  • Inheritance Example: class ElectricCar extends Car { ... }
  • Polymorphism Example: Method overloading and overriding.
  • Abstraction Example: Abstract classes and interfaces.
  • Encapsulation Example: Private fields with public getters and setters.

Let’s explore each concept to gain a deeper understanding of them.


What are Classes?

In Salesforce Apex, classes are fundamental units of code that define the behavior of objects. They encapsulate data and methods to operate on that data. Here’s how the description would look tailored to Salesforce Apex:

Apex classes are similar to object constructors used for creating custom objects and business logic within Salesforce. They serve as blueprints for creating instances of objects. Unlike traditional programming languages, Apex classes are stored on Salesforce servers and executed in a cloud environment. Apex classes consist of:

  • Modifiers: Decide who can access the class.
  • Class name: The name of the class, starting with a capital letter.
  • Superclass: If the class extends another class.
  • Interfaces: Contracts for what the class can do.
  • Body: Where the actual code of the class is written.

Apex classes are important for adding new features and customizing Salesforce to fit different business needs.

Class: Blueprint defining properties and behaviors.

  • Example:
public class MyClass {
    // Class variables
    public String name;
    public Integer age;
    
    // Constructor method
    public MyClass(String n, Integer a) {
        name = n;
        age = a;
    }
    
    // Method to display information
    public void displayInfo() {
        System.debug('Name: ' + name + ', Age: ' + age);
    }
}

In this example:

  • We have a class named MyClass.
  • It has two variables: name and age.
  • The constructor MyClass initializes these variables when a new instance of the class is created.
  • The method displayInfo prints out the name and age of an instance of MyClass.

This class can be used to create objects with names and ages, and then display their information.


What are Objects?  

In object-oriented programming (OOP) concepts, an “object” refers to a specific instance of a class. When we create objects from a class, they inherit the properties and behaviors defined by that class. These objects have attributes (states) and methods (behaviors) associated with them.

In OOP, objects are like real-world entities that we can interact with. They encapsulate data and functionality, making it easier to work with complex systems.

For example, if we have a class called “Car,” we can create objects like “Toyota” or “BMW” from that class. Each car object would have its own attributes such as color, model, and speed, as well as methods like “start” and “stop.”

So, in the context of object-oriented programming, objects are instances of classes that represent real-world entities and encapsulate both data and behavior.

Object: Instance of a class.

  • Example:
MyClass obj1 = new MyClass('John', 30);
obj1.displayInfo(); // Output: Name: John, Age: 30

MyClass obj2 = new MyClass('Alice', 25);
obj2.displayInfo(); // Output: Name: Alice, Age: 25
  • obj1 and obj2 are objects of the MyClass class.
  • Each object has its own data, in this case, name and age.
  • Objects can invoke methods defined in their class, like displayInfo(), to perform specific actions or display information based on their data.

What are Abstraction?  

In Salesforce Apex programming language, abstraction is a fundamental concept that allows developers to hide complex implementation details while providing essential functionalities to users. It enables developers to focus on what an object does rather than how it does it, promoting clarity, simplicity, and maintainability in code.

Example: Employee Salary Calculation

Let’s illustrate abstraction with an example of an Employee class in a Salesforce application for managing employee information. We’ll focus on calculating the salary of an employee, abstracting away the intricate details of the calculation.

public class Employee {
    // Attributes
    public String name;
    public Integer age;
    public Double hourlyRate;
    public Integer hoursWorked;
    
    // Constructor
    public Employee(String empName, Integer empAge, Double rate, Integer hours) {
        name = empName;
        age = empAge;
        hourlyRate = rate;
        hoursWorked = hours;
    }
    
    // Method to calculate salary
    public Double calculateSalary() {
        return hourlyRate * hoursWorked;
    }
}

Abstraction in Action

In the Employee class, the calculateSalary() method serves as an abstraction. It encapsulates the logic for calculating the salary, hiding the implementation details from the user. Developers interacting with this class don’t need to know how the salary is calculated they only need to use the calculateSalary() method.

Implementing Abstraction

Here’s how you can use the abstraction provided by the calculateSalary() method:

// Create an instance of Employee
Employee emp = new Employee('John Doe', 30, 20.0, 40);

// Calculate salary using abstraction
Double salary = emp.calculateSalary();

// Output the result
System.debug('Salary: ' + salary);

Benefits of Abstraction

By employing abstraction, you simplify the usage of your class and improve code readability. Developers interacting with the Employee class can focus on its functionalities without getting bogged down by implementation details. This promotes code reusability, easier maintenance, and enhanced collaboration among developers.


What are Inheritance?

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or subclass) to inherit properties and methods from another class (called a parent or superclass). In Salesforce Apex, inheritance enables developers to create efficient, reusable code by defining common functionality in a parent class and extending or customizing it in child classes.

Key Concepts:

  • Parent Class (Superclass): A class that defines common attributes and behaviors that are inherited by child classes.
  • Child Class (Subclass): A class that extends a parent class, inheriting its attributes and behaviors, and may also add its own unique attributes and behaviors.

Types of Inheritance in Salesforce Apex:

There are two main types of inheritance in Salesforce Apex:

  1. Single Inheritance
  2. Multi-Level Inheritance

1. Single Inheritance:

In single inheritance, a subclass inherits properties and methods from only one superclass.

Example:

Let’s say we have a superclass called Animal with a method makeSound().

public class Animal {
    public void makeSound() {
        System.debug('Generic animal sound');
    }
}

Now, we create a subclass called Dog that inherits from Animal and adds its own method bark().

public class Dog extends Animal {
    public void bark() {
        System.debug('Woof woof');
    }
}

In this example, Dog inherits the makeSound() method from Animal, and it also has its own method bark().

2. Multi-Level Inheritance:

In multi-level inheritance, a subclass can inherit properties and methods from a superclass, which in turn can inherit from another superclass.

Example:

Let’s extend our previous example. We’ll introduce another superclass called Mammal with its own method giveBirth().

public class Mammal {
    public void giveBirth() {
        System.debug('Giving birth to live young');
    }
}

Now, we’ll create a subclass called Dog that inherits from both Animal and Mammal.

public class Dog extends Animal {
    public void bark() {
        System.debug('Woof woof');
    }
}

In this case, Dog indirectly inherits the giveBirth() method from Mammal through the chain of inheritance (Dog -> Animal -> Mammal).

// Animal superclass
public class Animal {
    public void makeSound() {
        System.debug('Generic animal sound');
    }
}

// Mammal subclass extending Animal
public class Mammal extends Animal {
    public void giveBirth() {
        System.debug('Mammal giving birth to live young');
    }
}

// Dog subclass extending Mammal
public class Dog extends Mammal {
    public void bark() {
        System.debug('Dog barks: Woof woof');
    }
}

// Whale subclass extending Mammal
public class Whale extends Mammal {
    public void swim() {
        System.debug('Whale swimming gracefully');
    }
}

Note : Salesforce Apex supports only single inheritance in practice, though you can create class chains that resemble multi-level inheritance.


What are Polymorphism?

Polymorphism is a fundamental concept in object-oriented programming that allows objects of different types to be treated as objects of a common base type. In Salesforce Apex, polymorphism enables you to write generic code that can work with different types of objects, providing flexibility and reusability in your code.

Key Concepts:

  1. Base Types: In polymorphism, you define a base type or interface that specifies common behavior.
  2. Subtypes: Various concrete classes implement or extend this base type, each providing its own implementation of the common behavior.
  3. Runtime Binding: The specific implementation of a method is determined at runtime based on the actual type of the object.

Example:

Let’s consider a scenario where we have a base class Shape with a method calculateArea(). We also have subclasses Circle and Rectangle that extend the Shape class.

// Base class
public abstract class Shape {
    public abstract Decimal calculateArea();
}

// Subclass Circle
public class Circle extends Shape {
    Decimal radius;
    
    public Circle(Decimal radius) {
        this.radius = radius;
    }
    
    public override Decimal calculateArea() {
        return Math.PI * radius * radius;
    }
}

// Subclass Rectangle
public class Rectangle extends Shape {
    Decimal length;
    Decimal width;
    
    public Rectangle(Decimal length, Decimal width) {
        this.length = length;
        this.width = width;
    }
    
    public override Decimal calculateArea() {
        return length * width;
    }
}

Now, we can use polymorphism to work with objects of different shapes without knowing their specific types:

// Polymorphic usage
Shape shape1 = new Circle(5); // Creating a circle
Shape shape2 = new Rectangle(4, 6); // Creating a rectangle

Decimal area1 = shape1.calculateArea(); // Calculate area of circle
Decimal area2 = shape2.calculateArea(); // Calculate area of rectangle

System.debug('Area of Circle: ' + area1);
System.debug('Area of Rectangle: ' + area2);

Benefits:

  • Flexibility: You can write generic code that operates on objects of different types.
  • Extensibility: Easily add new types without modifying existing code.
  • Readability: Promotes cleaner and more modular code structure.

What are Encapsulation?

Encapsulation is one of the fundamental principles of object-oriented programming (OOP). It refers to the bundling of data and methods that operate on the data into a single unit known as a class. In simpler terms, encapsulation hides the internal state of an object from the outside world and only exposes the necessary functionalities through methods.

How Encapsulation Works

Encapsulation involves defining a class with private variables (data members) and public methods (member functions). The private variables can only be accessed and modified within the class itself, while the public methods provide controlled access to these variables from outside the class.

Example of Encapsulation in Salesforce Apex

public class BankAccount {
    // Private variables
    private Decimal balance;
    private String accountNumber;

    // Constructor to initialize variables
    public BankAccount(String accNum, Decimal initialBalance) {
        accountNumber = accNum;
        balance = initialBalance;
    }

    // Method to deposit money
    public void deposit(Decimal amount) {
        balance += amount;
    }

    // Method to withdraw money
    public void withdraw(Decimal amount) {
        if (amount <= balance) {
            balance -= amount;
        } else {
            System.debug('Insufficient funds');
        }
    }

    // Method to get account balance
    public Decimal getBalance() {
        return balance;
    }

    // Method to set account number (for demonstration purposes)
    public void setAccountNumber(String accNum) {
        accountNumber = accNum;
    }

    // Method to get account number (for demonstration purposes)
    public String getAccountNumber() {
        return accountNumber;
    }
}

Explanation:

  • The BankAccount class encapsulates the data (balance and accountNumber) and operations (deposit, withdraw, getBalance) related to a bank account.
  • balance and accountNumber are declared as private variables to restrict direct access from outside the class.
  • Public methods like deposit, withdraw, getBalance, setAccountNumber, and getAccountNumber provide controlled access to these private variables.
  • Users can only interact with the bank account through these methods, ensuring data integrity and security.

Benefits of Encapsulation

  • Data Hiding: Encapsulation hides the internal state of an object, preventing unauthorized access and manipulation.
  • Modularity: By encapsulating related data and methods within a class, code becomes modular and easier to maintain.
  • Controlled Access: Encapsulation allows controlled access to data, enforcing validation and business rules through methods.

What are interface?

In Salesforce Apex programming language, an interface is a blueprint for a class. It defines a set of methods that a class must implement. Interfaces help enforce a contract between different parts of your code, ensuring that classes that implement the interface provide specific functionality.

Key Points about Interfaces:

  1. Blueprint for Classes: Interfaces define a set of methods that classes must implement.
  2. Enforce Contract: Classes implementing an interface must provide implementations for all the methods defined in the interface.
  3. Promote Code Reusability: Interfaces enable multiple classes to share common method signatures, promoting code reuse.
  4. Facilitate Polymorphism: Interfaces allow you to treat different objects in a similar manner, enhancing polymorphism.

Example of Interface in Salesforce Apex:

Let’s say we want to create an interface called Shape which defines a method calculateArea().

// Define Interface
public interface Shape {
    // Method to calculate area
    Decimal calculateArea();
}

Now, let’s create a class Circle that implements the Shape interface.

// Implementing Interface
public class Circle implements Shape {
    Decimal radius;

    // Constructor
    public Circle(Decimal r) {
        radius = r;
    }

    // Method implementation
    public Decimal calculateArea() {
        return Math.PI * radius * radius;
    }
}

Similarly, let’s create another class Rectangle that implements the Shape interface.

// Implementing Interface
public class Rectangle implements Shape {
    Decimal length;
    Decimal width;

    // Constructor
    public Rectangle(Decimal l, Decimal w) {
        length = l;
        width = w;
    }

    // Method implementation
    public Decimal calculateArea() {
        return length * width;
    }
}

Now, we can use these classes and treat them uniformly through the Shape interface.

// Using Interface
Shape myShape1 = new Circle(5);
Shape myShape2 = new Rectangle(4, 6);

// Calculate areas
Decimal area1 = myShape1.calculateArea();
Decimal area2 = myShape2.calculateArea();

System.debug('Area of Circle: ' + area1); // Output: Area of Circle: 78.53981633974483
System.debug('Area of Rectangle: ' + area2); // Output: Area of Rectangle: 24.0

In this example, both the Circle and Rectangle classes implement the Shape interface, providing their own implementations of the calculateArea() method. This allows us to treat instances of these classes uniformly through the Shape interface, promoting code reusability and polymorphism.


What are abstract class?

Abstract classes in Salesforce Apex provide a blueprint for other classes to inherit from, but they cannot be instantiated on their own. They contain methods that must be implemented by any class that extends them. They serve as a template for creating related classes.

Key Points about Abstract Classes:

  1. Blueprint for Classes: Abstract classes provide a structure for other classes to follow. They define methods and properties that must be implemented by subclasses.
  2. Cannot be Instantiated: You cannot create an instance of an abstract class directly. It is meant to be extended by other classes.
  3. Force Implementation: Abstract classes enforce implementation of certain methods by subclasses. This ensures consistency and adherence to a predefined structure.

Example Code:

// Abstract class definition
public abstract class Animal {
    
    // Abstract method that must be implemented by subclasses
    public abstract void makeSound();
    
    // Concrete method
    public void sleep() {
        System.debug('Animal is sleeping');
    }
}

// Subclass of Animal
public class Dog extends Animal {
    
    // Implementation of abstract method
    public override void makeSound() {
        System.debug('Dog barks');
    }
}

// Subclass of Animal
public class Cat extends Animal {
    
    // Implementation of abstract method
    public override void makeSound() {
        System.debug('Cat meows');
    }
}

Usage:

// Instantiate subclass objects
Dog myDog = new Dog();
Cat myCat = new Cat();

// Call methods
myDog.makeSound(); // Output: Dog barks
myDog.sleep();     // Output: Animal is sleeping

myCat.makeSound(); // Output: Cat meows
myCat.sleep();     // Output: Animal is sleeping

In this example, Animal is an abstract class defining the method makeSound(). Both Dog and Cat classes extend Animal and implement the makeSound() method. The abstract class enforces the implementation of makeSound(), ensuring consistency in behavior across subclasses.


What are Access Modifiers:

n Salesforce Apex, access modifiers are keywords used to control the visibility and accessibility of classes, variables, and methods within the Salesforce platform. These modifiers play a crucial role in defining the scope of your code and managing interactions between different components.

Types of Access Modifiers:

Public: This is the default access modifier in Salesforce Apex. It allows the class, variable, or method to be accessed from anywhere within the same namespace or from other namespaces.

public class MyClass {
    public String myVariable;
    
    public void myMethod() {
        // Method implementation
    }
}

Private: A private modifier restricts access to the class, variable, or method within the same class. It cannot be accessed from outside the class.

public class MyClass {
    private String myVariable;
    
    private void myMethod() {
        // Method implementation
    }
}

Protected: The protected modifier allows access to the class, variable, or method within the same class and any subclasses. It is commonly used in inheritance scenarios.

public class MyClass {
    protected String myVariable;
    
    protected void myMethod() {
        // Method implementation
    }
}

Global: The global modifier makes the class or method available across different namespaces. It is used for exposing functionality to other Salesforce orgs or external systems.

global class MyClass {
    global String myVariable;
    
    global void myMethod() {
        // Method implementation
    }
}
Why Access Modifiers are Important:
  • Encapsulation: Access modifiers help in encapsulating data and functionality, allowing better control over how they are accessed and manipulated.
  • Security: By restricting access to certain components, access modifiers enhance the security of your code and prevent unintended access or modification.
  • Code Organization: They aid in organizing your codebase by clearly defining the visibility of classes, variables, and methods, making it easier to understand and maintain.

What are Virtual Keyword:

  • Definition: The virtual keyword in Salesforce Apex means that a method in a main class can be changed by another class.
  • Explanation: When a method is marked as virtual, it lets other classes change how it works. This makes it easy to create different versions of the same method.

Example with Code:

public virtual class Vehicle {
    public virtual void start() {
        System.debug('Vehicle starting...');
    }
}

In this example, the Vehicle class has a method called start() that can be changed by other classes. So, if we have a class for cars, bikes, or trucks, each of them can have their own way of starting.


What are Override Keyword:

  • Definition: The override keyword in Salesforce Apex shows that a method in a class is going to replace a method from another class.
  • Explanation: When a method has override, it means that a class is making its own version of a method it got from another class. This helps in making each class behave differently even if they share the same method name.

Example with Code:

public class Car extends Vehicle {
    public override void start() {
        System.debug('Car starting...');
    }
}

In this example, the Car class is saying that it wants to change how the start() method works, which it got from the Vehicle class. So, when a Car wants to start, it will follow the instructions in its own start() method, which prints “Car starting…”.

  • Flexibility in Inheritance: The virtual keyword allows methods to be changed easily by other classes, making it simple to customize behavior.
  • Method Replacement: With override, classes can clearly show that they are making their own versions of methods they got from other classes.
  • Customization: By using virtual and override, developers can make classes that can be changed and customized easily, helping to reuse code and make programs easier to manage in Salesforce Apex.

Conclusion:


In conclusion, mastering Object-Oriented Programming (OOP) concepts in Salesforce Apex is like learning how to build with Lego bricks – it’s about understanding the basic building blocks that make up your code.

By grasping ideas like objects, classes, encapsulation, inheritance, polymorphism, and abstraction, developers can create code that’s organized, easy to understand, and can adapt to different situations. These concepts help in building flexible and efficient solutions on the Salesforce platform, ensuring that developers can create powerful applications that meet the evolving needs of businesses.

Leave a comment