I was pretty confused by interfaces at first, but a friend of mine explained it really well. So, I'll try and regurgitate (sp?) his explanation:
Basically an interface is a contract. When you declare a class:
<CODE>
public class Peanut implements Smashable
{
//code for being a peanut
//plus code to implement methods declared in Smashable, say ...
//smash(), grind(), and mangle()
}
</CODE>
You are promising that all instances of class Peanut will be able to handle the methods contained in Smashable.
Now imagine that we have a bunch of classes implementing Smashable (eg. Walnut, Hazenut, CuteFuzzyKitten). All these classes promise to be able to handle the methods declared in Smashable.
We can now create a method like this:
<CODE>
public void Pulper ( Smashable[] stuffToPulp )
{
//Code that calls smash, grind and mangle on Smashable objects.
}
</CODE>
The advantage here is that you can put peanuts, walnuts and CuteFuzzyKittens all together in that same array and treat them as objects of the same type (type = Smashable).
I'm sure there are probably other uses for interfaces. They basically exist to make up for the fact that, unlike C++,
java doesn't support multiple inheritance. But I've never worked in C so I dunno all the implications of this.
I imagine that in large projects interfaces become very useful for isolating your classes from the clients that use them. But I'm not really working at that level yet so 'tis pure conjecture.
Hope that helps,
Joe
[This message has been edited by Joe Von (edited March 07, 2001).]
[This message has been edited by Joe Von (edited March 07, 2001).]