If you declare bunchOfStrings
as a List
, you can't call any of the ArrayList
methods (without casting), even though it is pointing to an ArrayList
object -- you can only call methods that are declared in the List
class.
For this reason, you might think that it's better to always declare your variable type to be as specific as possible, but declaring it as a List
is generally preferable because it allows you to change the underlying implementation of your List
without having to change anything else in your code. You can easily modify your code as follows without breaking anything else in your code:
List<String> bunchOfStrings = new LinkedList<String>();
As a rule of thumb, only ever declare the type of your variable to be a specific subclass if you...
- ...need access to methods that are only available in the subclass.
- ...need to pass the object instance to a method that only accepts objects of that subclass.