Interfaces in Salesforce Apex

Interfaces in Salesforce Apex

On January 22, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on Interfaces in Salesforce Apex
Interfaces in Salesforce Apex
Interfaces in Salesforce Apex

Table of Contents

What is an Interface?

An Interface is similar to a class having methods without a body that means only method signature is available in the Interface but the body of the methods is empty. To use an Interface in class, the body of all the methods contained in the interface must be implemented in the Apex class. Interface keyword is used to create an apex interface.

Here’s a simple example to explain how an interface works in Salesforce Apex:

Interface Definition:

This code snippet demonstrates how to define an interface in Apex. The interface contains method signatures that any implementing class must define.

public interface Vehicle {
    // Method signatures without implementation
    void startEngine();
    void stopEngine();
}

Implementing the Interface:

Here, we implement the PaymentProcessor interface by providing concrete logic for the processPayment() method in the CreditCardPayment class.

public class Car implements Vehicle {
    // Providing implementation for the startEngine method
    public void startEngine() {
        System.debug('Car engine started.');
    }

    // Providing implementation for the stopEngine method
    public void stopEngine() {
        System.debug('Car engine stopped.');
    }
}

Usage:

This snippet shows how to use the interface in a class by passing an object that implements PaymentProcessor to a method that executes the defined behavior.

public class InterfaceExample {
    public static void demo() {
        Vehicle myCar = new Car();  // Using the interface reference
        myCar.startEngine();        // Calls the startEngine method
        myCar.stopEngine();         // Calls the stopEngine method
    }
}

Explanation:

  • Interface: Vehicle defines two method signatures (startEngine() and stopEngine()), but there is no code within the interface to actually perform those actions.
  • Implementation: The Car class implements the Vehicle interface and provides the actual logic for startEngine() and stopEngine().
  • Usage: In the InterfaceExample class, we create an instance of Car using the Vehicle interface reference. We can call the methods defined in the interface, which are implemented by the Car class.

This allows for flexibility and polymorphism, as different classes (like Car, Bike, etc.) can implement the same interface but with different behaviors.

Dive into these essential Salesforce interview questions and answers for a thorough understanding and profound insights into Salesforce Admin, Developer, Integration, and LWC topics.

How to use interfaces in Apex?

In Apex, interfaces define a set of method signatures without implementing their logic. Classes that implement the interface must provide concrete implementations of all the methods defined in the interface. Interfaces allow for flexibility and code reusability by enabling different classes to share common behavior while maintaining their unique implementations. This promotes consistency and abstraction in Salesforce applications.

Code Snippet 1: Defining an Interface

public interface PaymentProcessor {
    void processPayment();
}

Explanation:
This defines an interface called PaymentProcessor with a single method processPayment() that any implementing class must define. There is no implementation here, just the method signature.

Code Snippet 2: Implementing the Interfac

public class CreditCardPayment implements PaymentProcessor {
    public void processPayment() {
        System.debug('Processing credit card payment.');
    }
}

Explanation:
The class CreditCardPayment implements the PaymentProcessor interface. Since it implements the interface, it must provide the concrete logic for the processPayment() method. In this case, the method prints a message to the debug log.

Code Snippet 3: Using the Interface in a Class

public class PaymentService {
    public void executePayment(PaymentProcessor processor) {
        processor.processPayment();
    }
}

Explanation:
In this example, the PaymentService class has a method executePayment() that takes any object implementing the PaymentProcessor interface as a parameter. This allows for flexible processing, as different implementations of PaymentProcessor (like CreditCardPayment) can be passed to this method.

Checkout: Data types in Salesforce Apex

Interfaces in Apex example

Let’s take a simple example of an interface and how we can implement it in different apex classes. Suppose a company has two types of purchase orders, one from customers and the other from employees. So, the company has to provide discounts based on the type of purchase order.

Here, we will create a DiscountPurchaseOrder Interface

// An interface that defines what a purchase order looks like in general
public interface DiscountPurchaseOrder {
    // All other functionality excluded
    Double discountOnOrder();
}

Note: DiscountPurchaseOrder is an abstract interface that defines a general prototype. Access modifiers are not specified for the method defined in an interface; it contains only the method signature.

Read more: Salesforce apex programming examples

The EmployeeOrder class implements the DiscountPurchaseOrder interface for Employee purchase orders.

// One implementation of the interface for Employees
public class EmployeeOrder implements DiscountPurchaseOrder {
    public Double discount() {
        return .08;  // For Employees discount should be 8%
    }
}

Another class CustomerOrder implements the DiscountPurchaseOrder interface for Customer purchase orders.

Readmore: Strings in Salesforce Apex

// Another implementation of the interface for customers 
public class CustomerOrder implements DiscountPurchaseOrder {
      public Double discount() {
        return .04;  // For customers discount should be 4%
      } 
}

Note: You can see that both the CustomerOrder and EmployeeOrder classes implement the DiscountPurchaseOrder interface, so the DiscountPurchaseOrder interface body must be defined in the Discount method of the class. All methods of an interface must be defined in the class that implements the interface.

CRS Info Solutions provides a dynamic and comprehensive Salesforce online course, perfect for beginners aiming to launch a successful career in the Salesforce ecosystem. Our program covers all the vital areas required to thrive in Salesforce, including administration, development, and Lightning Web Components (LWC). By focusing on these core areas, we ensure learners are well-prepared to manage Salesforce platforms, build custom applications, and design modern, user-friendly interfaces using LWC. Whether you are new to Salesforce or looking to enhance your foundational knowledge, our course offers an ideal environment for learning and growth.

Alongside teaching key technical concepts, our Salesforce online course includes essential Salesforce interview questions and extensive certification preparation to equip students for real-world scenarios. We offer daily notes, real-life examples, and consistent support to help beginners understand complex topics more easily. Recognizing the importance of interview readiness, we also provide strategic job preparation guidance throughout the course. With practical, hands-on experience, mock interview sessions, and insights into frequently asked Salesforce interview questions, our students gain the confidence they need to succeed in the competitive job market.

Moreover, our course is specifically designed to help students excel in Salesforce certification exams. We provide step-by-step support throughout the certification process, ensuring learners focus on crucial exam topics while building practical expertise. By the end of the course, students will not only be prepared to pass their Salesforce certification exams but will also be equipped with the skills and knowledge needed to pursue rewarding job opportunities within the Salesforce ecosystem.

Next chapter is DML and previous chapter is Objects in Apex.

Comments are closed.