In java to implement multiple inheritance we use interface.Is it the only use of interface?If yes what is the main use of interface in java?why we need interface in java?
I would say the main use is polymorphism, or the ability to perform the same operation on a number of different objects. If different objects all implement the same interface and have the same method, you can store all of those objects in a Vector, for example, and iterate through the Vector calling that method on each one.
You need them so you can type your objects outside the hierarchy.
For example, the objects that can be compared can be pretty much anywhere on the object hierarchy - they do not need to have a common ancestor which can be compared. String
s can be compared, Integer
s can be compared, you could even make your own Frame
s that could be compared (say, a frame is "less" than another frame if it is more in the foreground - i.e. if it would overlay the other frame). Thus, if you want to refer to a thing that can be compared, you would be forced to declare a variable with the most general ancestor - in this case, Object
. This is too general, because then it can also receive values which are not comparable (and would throw errors when you try to compare them).
Thus, the interface Comparable
: it selects all the classes that implement the comparison functionality across the subclass-superclass hierarchy.
In addotion to these responses I would say the most important use for interfaces is to reduce coupling between components in your software.
An interface allows to represent an agreement between classes on how they will talk to each other without being tied to the actual implementations.
This alllows us to replace implementations by others (very useful for testing!) without changing the compiled code.