I have a confusion in different ways the objects are created which I have seen in java docs and other programming books. For e.g.
Assuming there is a base class
and a derived class
1- I have a variable of type Base
which refers to the object of type Derived
List<String> list = new ArrayList<String>();
2- I have a variable of type Derived
which refers to the object of type Derived
ArrayList<String> arrList = new ArrayList<String>();
My question is what should be my thinking while choosing between 1 and 2? Is it to take advantage of Polymorphism
in general Base-Derived scenarios?
Is there a better practice
while choosing between 1 and 2 that I am not aware of or is it just a personal decision
?
EDIT:
Sorry, List is an interface. Another question: Will my decision change if I use a Type parameter?
ArrayList<T> list = new ArrayList<T>();
Update Answer: This is actually called "Programming to the interface"
. Thanks Code-Guru. Exactly what I was looking for is explained in very simple terms in one of the answers to this question - What does it mean to "program to an interface"?