Reputation: 20882
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"?
Upvotes: 1
Views: 160
Reputation: 3793
In the case where List is a class ( just assume for the purpose of answering your question - "Shall we use object of Parent class representing child class or use object of type derived class ( actula class) ? "
1) You were correct, its solely for the purpose of polymorphism.
2) Mostly its used for Passing the object around different class methods. Other classes' methods may be accepting parent class a input. you have to use the casting in those places.
Upvotes: 1
Reputation: 65879
List
is not a base class it is an interface
and therefore should be used wherever possible.
Using the interface that a class implements allows you to work with all classes that implement the interface, not just the specific class.
String
is a concrete class so it is much clearer to use it directly.
Sometimes, however, even though String
implements the CharSequence
interface it is unnecessary to use CharSequence
because it would just be confusing. However, take a look at StringBuilder
, it uses CharSequence
almost exclusively.
In summary - there is no better there is just appropriate.
Upvotes: 4
Reputation: 2833
Choosing the base type allows you to at some point in the future change between using an ArrayList to say a LinkedList, without changing the rest of the code. This gives you more flexibility to refactor later on. Likewise, your public methods should return a List instead of the specific type of List implementation for the same reason -- so that you may change your internal implementation to optimize performance without breaking the contract to your callers.
Upvotes: 3