Using interfaces in APIs
by, 05-25-2011 at 09:59 AM (3243 Views)
When you are designing your API, you might want to use interface since this seems a common practice. There exist a style in Java programming where everything is expressed in terms of Java interfaces instead of classes.
Using interfaces provides benefits but its not a good idea for an entire API to be expressed in terms of them.
Use interface as a type if you have a good reason for it to be. Following are some important facts to be considered:
Interfaces can be implemented by anybody so you can not be sure that a class implementing this interface obeyed the semantics you expect.
It is seen that implementations of APIs that are defined entirely in terms of interfaces often end up cheating and casting objects to the non-public implementation class.
Interfaces cannot have constructors or static methods.
Interfaces cannot evolve. For instance you add a new method to an interface in version 2 of your API. Then user code that implemented the interface in version 1 will no longer compile because it doesn't implement the new method.
Using abstract class instead of an interface is a better choice since you don't have this problem.
Do note that Interfaces cannot be serialized.
There are few good things with using interfaces in APIs. Ill shed some light on those.
If the interface is intended to be implemented by user code, then it is often more appropriate than an abstract class. This positive point remains as long as interface has just one method. If there are several methods and an implementation class only needs to do something in one of them, then it's annoying to implement all the others. Another negative is that if an interface has 3 methods today and you add one method to it tomorrow, then all the implementations will be revised.
Interfaces prove useful to avoid multiple inheritance.
The java.lang.reflect.Proxy class allows you to make an implementation of any interface at runtime, where calling any of the interface's methods results in a call to a single invoke method. You may not construct a dynamic proxy for an abstract class, so if you think it will be useful for users to make dynamic proxies that is one reason to favour an interface.
Last word: Plan your interfaces logically. Use only if you really need to.