Sunday, October 28, 2012

Why do we need interfaces in java?

Implementing an interface allows a class to become more formal about the behavior it promises to provide also they form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

the idea about interfaces is, it tells the user what kind of operations can be done on the objects of that certain class without having the user concerned about the implementation of these methods..for example if you open the java API and check out class String, you will find a list of methods..these methods are the interface of the class, and these are the operations that could be done on a String..yet the user doesnt know anything about the implementation of these methods 

the important of interface is to organize your code ... by collecting all related methods in one interface and then implement those methods in any class implement this interface.
it really useful if your class is very large and have a lot of methods.



Interfaces allow me to abstract objects so that I can have a collection of say Animals without careing what kind of Animals are in the collection.

Interfaces for the key to many design patterns. 
Interfaces are key to most application frameworks.
Interfaces increase abstraction allowing us to make more and more generalized designs (and thus fancy application frameworks).

No comments:

Post a Comment