The key is polymorphism. In the first line of code, we can only have access to the methods defined in the List interface. Additional methods defined in ArrayList which implements List, cannot be used by the first line of code.
The key is polymorphism. In the first line of code, we can only have access to the methods defined in the List interface. Additional methods defined in ArrayList which implements List, cannot be used by the first line of code.
This is not exactly true, in the first line of code we can only access the methods defined in the List interface, unless we explicitly downcast the instance to an ArrayList. For e.g.
It should be noted however that downcasting is not recommended unless, one is sure that the superclass object is a subclass object.
David Harkness
Ranch Hand
Joined: Aug 07, 2003
Posts: 1646
posted
0
Originally posted by Nigel Browne: It should be noted however that downcasting is not recommended unless, one is sure that the superclass object is a subclass object.
And you can do that with
Raj Joe
Ranch Hand
Joined: Oct 15, 2004
Posts: 41
posted
0
Originally posted by Cheng Wei Lee: Hi,
The key is polymorphism. In the first line of code, we can only have access to the methods defined in the List interface. Additional methods defined in ArrayList which implements List, cannot be used by the first line of code.
For e.g.,
HTH.
I have seen that people recommend the below style List listA = new ArrayList(); Is there any advantage?
Ernest Friedman-Hill
author and iconoclast
Marshal
Yes. It you write code this way, then if you later decide that a LinkedList would work better in your application, then you can just change this one line of code, and everything is guaranteed to still work. In general, using the least specific possible reference types makes your application easier to modify.