Monday, October 29, 2012

What is an interface in java

Basically, interface is a keyword in java. It is used for abstraction. Since multiple inheritance is not allowed in java, we are using interface to acheive the multiple inheritance.

All variables inside the interface is implicitly public and final constants and all the methods inside the interface is also public. We can call the variables just by calling the interface name.variable name.

An interface can extends as many of the interfaces whereas java class can extend only one class implements many.

We cannot define concrete methods in interfaces. Interfaces are pure Abstract class. If we implement the interface to a particular class, then that class must implement all the methods inside that interface. if we didn't implement all the methods then that class must be declared as a Abstract class.

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).