Interface provides the base for the concrete classes. It defines the contract which must be full filled by the implementing classes. So it can be use full in case where you need polymorphism. for example if you have some classes and interface like:
Here if you want to do some generic work which is common for both the doctors (doCheckUp) you should use the interface like
In this case no matter which object you are passing it will call the doCheckUp method of corresponding object.
But your concrete class can have some extra methods and if you want to use those methods then you have to call the methods using corresponding concrete class objects.
So If you want to use the generic common methods, you should use the interface instance.
For example in case of ArrayList and List you can not user ensureCapacity method using List interface reference because this method does not come under List contract. It is defined in ArrayList itself.
Just one thing to add to the "contract" notion..... when you refer to an object by interface all that you can reference are the methods/properties defined by the interface... nothing else. So, in effect, you are locking callers out of anything except the methods/properties of the interface. That is the part that limits the "coupling". The code that references the object knows the other object only by the interface... so any object that implements the interface can be "plugged in" without a problem.
SCJP - 86% - June 11, 2009
Bob Ruth wrote:The code that references the object knows the other object only by the interface... so any object that implements the interface can be "plugged in" without a problem.
Sorry for waking up the zombies, but one question. If I used
and still used only the methods of List that were overridden by ArrayList(like get, add and not ensureCapacity), there ain't any coupling trouble, right? I mean if I blindly replaced ArrayList usage with Vector, there still won't be any problem. So what exactly does a reference to an interface offer you? Or is it just a programming convention?
Coderanch, best ever forum on the net. Hands down.
We don't have time for this. We've gotta save the moon! Or check this out:
Free, earth friendly heat - from the CodeRanch trailboss