This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Java in General and the fly likes why use interfaces at all? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "why use interfaces at all?" Watch "why use interfaces at all?" New topic

why use interfaces at all?

budsy remo
Ranch Hand

Joined: Sep 20, 2008
Posts: 103
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 ?
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45294
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.
Valery Lezhebokov
Ranch Hand

Joined: Jun 12, 2006
Posts: 39
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.

Hope this helps.

SCJP 1.5, OCE EJB 3.x
I agree. Here's the link:
subject: why use interfaces at all?
It's not a secret anymore!