Saturday, February 21, 2009

Interface

We use interface to achieve polymorphism. In simple english, the users of your class will have a reference of the interface rather than the class which actually implement that method. This is an object oriented principle that enforce 'keeping the concerns separate' and 'program to super class/interface rather than sub class'. For example: assuming Calculator is an interface, the users of your controller are allowed to call getCalculator to get it. Now, for users, the point of contact is 'Calculator', they shouldn't be interested which class actually implemented the Calculator interface to provide the logic.
public Calculator getCalculator() {
return new BasicCalculator();
}
In future version, you can change the logic, and your users will not be bothered, for example, in an overridden method:
public Calculator getCalculator()
{return new EnhancedCalculator();}
Take an example of T.V, you will see that the remote control is the Interface to your T.V functions. If some Functions are subjected to change/enhanced there should be no effect on the interface/remote control in this example.
Plus if you don't want to expose your logic to some one, (means you don't some one to share your code) you can give him you interface, a standard way to use your logic.

"Interface is like defining some protocol.
When you start building some module or package you must code it into some proper manner so if someone else wants to update or work on it, its working is clear for them. Means it should be generic code. So instead of starting whole thing into single class, you thing about some generic methods, constants your module needed, without thinking of its implementation. So here comes the concept of Interface and Abstract Classes.
When you start implementing method define in Interface you start working with classes which implementing your interface. "

No comments:

Post a Comment