Newer Version Available
Interfaces
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.
Here is the definition of the PurchaseOrder interface.
1// An interface that defines what a purchase order looks like in general
2public interface PurchaseOrder {
3 // All other functionality excluded
4 Double discount();
5}This class implements the PurchaseOrder interface for customer purchase orders.
1// One implementation of the interface for customers
2public class CustomerPurchaseOrder implements PurchaseOrder {
3 public Double discount() {
4 return .05; // Flat 5% discount
5 }
6}This class implements the PurchaseOrder interface for employee purchase orders.
1// Another implementation of the interface for employees
2public class EmployeePurchaseOrder implements PurchaseOrder {
3 public Double discount() {
4 return .10; // It’s worth it being an employee! 10% discount
5 }
6}- The interface PurchaseOrder is defined as a general prototype. Methods defined within an interface have no access modifiers and contain just their signature.
- The CustomerPurchaseOrder class implements this interface; therefore, it must provide a definition for the discount method. Any class that implements an interface must define all the methods contained in the interface.
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.
See also Classes and Casting.