Can you avoid changing the code you have already written and tested to add new functionality? Can you add new classes to your program without having to recompile the whole thing? The answer to both questions is yes, and as you might have guessed, is based on interfaces and dynamic class loading.
As an aside, most of the classes and architecture used in this article are simplified from their use in professional programming. The overall code demonstrates how to use interfaces to dynamically extend programs; it is not intended for use in real systems.
An interface simply describes the way an object is called. When you define an interface, you relate how other objects will use a specific object.
Most of you working with Java should already understand interfaces, as it is difficult to use Java without that knowledge. But for those of you unclear on the subject, I'll start at the beginning and then create more complicated examples. If you already understand interfaces, you can probably skim until we get to the Using Strings to Specify Class Name section.
The first example illustrates the power of interfaces. Assume your client is a brokerage house, and they want you to set up their trading system. They trade in all sorts of financial instruments: stocks, bonds, commodities, and so on. Different customers are charged different amounts for their trades; the amounts are defined by what the client calls pricing plans.
First, you think about the design of your classes. The main classes and their properties, defined by the client, may be as follows:
Customer: Name, Address, Phone, PricingPlanTrade: TradeType (stock, bond, commodity), ItemTraded (stock symbol), NumberOfItemsTraded, ItemPrice, CommissionAmountPricingPlan: Provides a call procedure to calculate the CommissionAmount for a trade
You can code the pricing plans without using an interface and then enhance the code from there. Right now, the client has two pricing plans defined as follows:
The Trade object uses a PricingPlan object to calculate how much commission to charge the customer. You create a PricingPlan class for each pricing plan. The class for Plan 1 is called PricingPlan20 and Plan 2's class is called PricingPlan1510. Both classes calculate the commission to charge using a procedure called CalcCommission(). The code looks like the following: