Wednesday 29 August 2012

Interfaces - Apex

An interface is a named set of method signatures (the return and parameter definitions), but without any implementation.  Interfaces provide a layer of abstraction to your code. They separate the specific implementation of a method from the declaration for that method. This way, you can have different implementations of a method based on your specific application. For example, a fridge is a type of kitchen appliance, and so is a toaster. Since every kitchen appliance has a model number, the corresponding interface can have a getModelNumber method. However, the format of the model number is different for different appliances. The Fridge class and the Toaster class can implement this method such that they return different formats for the model number.
Interfaces can be handy—they specify a sort of contract. If any class implements an interface, you can be guaranteed that the methods in the interface will appear in the class. Many different classes can implement the same interface.
Try it out by creating an interface that is implemented by the Fridge and Toaster classes.
  1. Create an interface in the same way that you create a class:
    public interface KitchenUtility {
    
      String getModelNumber();
    
    }
  2. Modify your Fridge class to implement this interface. Simply add the words in bold to the definition of the class on the first line.
    public class Fridge implements KitchenUtility {
    
  3. Now define a new class called Toaster that also implements the KitchenUtility interface.
    public class Toaster implements KitchenUtility {
    
        private String modelNumber;
    
        public String getModelNumber() {
            return 'T' + modelNumber;
        }
    
    }
    Because both the Toaster and Fridge classes implement the same interface, they will both have a getModelNumber method. You can now treat any instance ofToaster or Fridge as a KitchenUtility.
  4. The following example creates an instance of a Fridge and Toaster. It then creates an array of KitchenUtility objects using these two objects and treating them as KitchenUtility instances.
    Fridge f = new Fridge('MX', 200);
    Toaster t = new Toaster();
    KitchenUtility [] utilities = new KitchenUtility[] { f, t };
    String model = utilities[0].getModelNumber();
    System.debug(model);

No comments:

Post a Comment