if I assign a derived class instance to the reference of base interface,what is the advantage like this BaseInterface b=new Derived class().All the methods in the base interface needs to be implemented in derived class and all the public static final variables will be inherited by the derived class,so there is no question of runtime decision to be made
This is usefull when you are switching over multiple methods with the same reference. I can give you an example of List and ArrayList. [CODE] List li = new ArrayList(); [\CODE]
Now in above example if you pass your li varaible into any other method which is using any other implementation of List then it will be tedious to take another variable and then transform this "li" varaible to any other Class type. So it's better in these sort of Situtaions.
The Best way to predict your future is to create it - Every great individual common man
To elaborate that a bit more. If I write a method like this:
You can call it with an ArrayList argument. But suppose you discover LinkedList performs better in the rest of your program, so you change to using a LinkedList. You'll have to convert it to an ArrayList or change my method. We try to avoid this kind of restriction when we can.
What if I coded:
Now you can call it with ArrayList, LinkedList or some future List that Sun or somebody else makes up. My method is more flexible and you are more free to change what you do.
This is just one example of how "code to interfaces" makes code easier to change, or less necessary to change. Does that sound worth doing?
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Oct 21, 2005
say I do like this and send a linked list reference to a method that accepts list and if I return the list will the insertion order be still maintained
Joined: Jan 29, 2003
Referring to a List by the interface just means the compiler will let you use the methods defined on the interface. The implementation that is sent in will behave just as it always does when you call those methods. So if you make a list that maintains insertion order it should keep right on doing that.
Something not mentioned before: if LinkedList or ArrayList have methods beyond what's defined on the interface, I won't be able to call them from myMethod. If I find I need to call some special method on a particular subclass, it's often a sign to rethink my design. That's rather advanced so don't fret over it too much just yet.