Salesforce Apex Tutorial Chapter 15: Apex Interfaces

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.
Interfaces are used to provide abstractions to your code. They separate the particular implementation for a method from the declaration for the method. In this manner, you can provide different implementations of a method for different applications.
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.
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.
// 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.