This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
if interfaces are mere something that a class implements by giving definitions then why use interfaces at all ?
Why not just have a class with a method that defines a method and then we use it .
One of the explanations i got in a book was
Java is strongly typed.When making a method call the compiler needs to be able to check that the method actually exists .
then it gave an example:-
//rearrange a[i] and a[j]
The compiler must know that a[i] actually has a compareTo() method .
Now asuuming class did not implement comparable interface but defined a method compareTo() then still the compiler would have been able to know that a[i] has a compareTo() method or not , so again why use interfaces at all ?
No, it is not at all easy for the compiler to check that an object passed to methods like Collections#sort(List). It is much easier to say the parameter type is List<Comparable>, which means the members of the List have to be Comparable (the generics is actually more complicated than that). So the elements would have to extend the Comparable class. But you can't extend two classes. If Comparable is an interface, you can implement several interfaces; look at the String class for example.
For me the real power of the interfaces is in decoupling components, and that becomes more important in large applications. Interfaces define behavior, while classes define how this behavior is achieved. E.g. you might have an interface
and several implementations of this interface which load properties from different sources like XML, DB, file etc. Then in the main (or any other class) you may create the loader and use interface reference to point to it:
After creating you can pass the loader around to any number of methods/classes, and if in some time you decide to load your properties from a DB, all you will need to do is to change one line:
without touching the rest of the code.