views:

102

answers:

2
+3  Q: 

Polymorphic call

I am new to java, I have seen in the code at many places where my seniors have declared as

List myList = new ArrayList(); (option1)

Instead of

ArrayList myList = new ArrayList(); (option2)

Can you please tell me why people use Option1, is there any advantages?

If we use option2, do we miss out any advantages or features?

+8  A: 

Option 1 is considered programming to an interface, where option 2 is programming to an implementation. The latter is sometimes necessary, but the former provides you with the ability to easily switch implementations by ensuring that you don't depend on methods provided by a particular implementation.

Furthermore, if you create methods that need only the functionality provided by an interface then they should be declared as requiring the interface so that any object implementing the interface can be passed to them. Doing so broadens the scope for re-use of the API. For example:

// This can be called passing any List
public int countItems(List lst, Filter flt) {
    // iterate list, apply filter, and count matching objects
    }

// This can called passing only an ArrayList, an unnecessary limitation in this case
public int countItems(ArrayList lst, Filter flt) {
    // iterate list, apply filter, and count matching objects
    }

That said, for some interfaces, there are hidden implementation dependent traps (at least in Java). An example of this in List.get(int); if you have an ArrayList this is efficient, but for a LinkedList it is not. If the list is very large the difference can be dramatic, esp for a poorly conceived construct like this loop:

for(int xa=0,len=list.length; xa<len; xa++) {
    Object obj=list.get(xa);
    obj.doSomething();
    }

which has terrible performance for large lists since the list must be traversed from the beginning for every get(xa).

Software Monkey
The explanation is good, but I don't think it's appropriate to mention efficiency of the Java Collections Framework here. JCF implementation is about algorithm, while harigm is talking about OO Principles
phunehehe
@Phunehehe: When the OO principle is directly related to enabling transparent substitution of the implementation, it seems quite appropriate to discuss potential traps in doing so.
Software Monkey
+2  A: 

The advantage of using option1, ie, List myList = new ArrayList(); is to have polymorphic behaviour with respect to methods. Say, for example, you can have a method which takes arguments of type List,

someMethod(List lst)
{
   lst.doSomething();
   //do somethng else.....
}

In this method lst can be of type Linked List, ArrayList or CopyOnWriteArrayList.

Zaki
@Zaki,can you contribute to my techincal website ?
harigm
@harigm, Id like to.
Zaki
@Zaki, techification dot com is the site, i am working on the site, will update you
harigm