Interfaces and Extending Classes

An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface.

Interfaces can 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.

Defining an interface is similar to defining a new class. For example, a company might have two types of purchase orders, ones that come from customers, and others that come from their employees. Both are a type of purchase order. Suppose you needed a method to provide a discount. The amount of the discount can depend on the type of purchase order.

You can model the general concept of a purchase order as an interface and have specific implementations for customers and employees. In the following example the focus is only on the discount aspect of a purchase order.

public class PurchaseOrders {
 
    // An interface that defines what a purchase order looks like in general 
    
    public interface PurchaseOrder {
        // All other functionality excluded 
    
        Double discount();
    }
 
    // One implementation of the interface for customers 
    
    public virtual class CustomerPurchaseOrder implements PurchaseOrder {
        public virtual Double discount() {
            return .05;  // Flat 5% discount 
    
        }
    }

   // Employee purchase order extends Customer purchase order, but with a  
    
   // different discount 
    
    public class EmployeePurchaseOrder extends CustomerPurchaseOrder{
          public  override Double discount() {
            return .10;  // It’s worth it being an employee! 10% discount 
    
        } 
   }    
}
Note the following about the above example:

When you define a new interface, you are defining a new data type. You can use an interface name in any place you can use another data type name. If you define a variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface, or a sub-interface data type.

An interface can extend another interface. As with classes, when an interface extends another interface, all the methods and properties of the extended interface are available to the extending interface.

See also Classes and Casting.

You cannot add a method to an interface after the class has been uploaded in a Managed - Released package version. For more information about managed packages, see Developing Apex in Managed Packages.

© Copyright 2000–2012 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.