0

Suppose for a program that I needed a List of some kind. Any kind of List will do, so I create one.

List<Integer> example = new LinkedList<Integer>();

I've heard that it's good practice, when instantiating your objects, to define them as interfaces, if you are doing something that requires the use of that interface, but not necessarily that specific concrete class. For example, I could have made that "example" list an ArrayList instead.

However, defining my LinkedList to be a List interface in this way limits me. I can't use any of the LinkedList-specific methods, for example. I can only use methods that are in the List interface itself. The only way I've found to use my LinkedList-specific methods are to cast example to a LinkedList, like so:

((LinkedList)example).addLast(1);

...which seems to defeat the purpose, since by casting "example" to be a LinkedList, I may as well have created it and defined it to be a LinkedList in the first place, instead of a List.

So why is it good practice to create concrete classes and define them via interface? Is there something that I am missing?

Edmis
  • 31
  • 1
  • 1
  • 3
  • If you absolutely need to use non-inherited methods in the concrete class, then you will want to declare the variable as a variable of the concrete class type. Life is full of trade-offs, and by doing this you are trading off some flexibility. The other option is to write your code so that it does not need to use the non-inherited concrete methods and does not need to do casting (which defeats the purpose here). – Hovercraft Full Of Eels Jun 26 '16 at 22:18
  • 4
    The good practice is to declare the variable using the top-most interface of what you want to represent. If you want to represent a type from which you can call `addLast`, don't use a `List`, but use a `Deque`. – Tunaki Jun 26 '16 at 22:19
  • Using interfaces instead of concrete types makes most sense to me in the case of method parameters. Offering the user more flexibility in what type to pass, can be a good thing. A counter example would be ```String``` instead of ```CharSequence``` since ```String``` offers immutability. – Jorn Vernee Jun 26 '16 at 22:24
  • See also this answer http://stackoverflow.com/a/383954/1743880 – Tunaki Jun 26 '16 at 22:24
  • The javadoc says `addLast` is equivalent to `add`, which is defined for all `List` types. So if your only issue is that you want to use `addLast`, it isn't an issue. Just use `add`. (The javadoc also says `add` is an optional operation not supported by all `List`s, but I think the only `List`s that don't support it are the ones that provide a _read-only_ or "immutable" view.) – ajb Jun 27 '16 at 00:52

1 Answers1

0

LinkedList implements several interfaces.

The method addLast() comes from the Deque interface. It could be that's the interface you want to use.

Alternatively you might just need a List, in which case the add() method will append to the list.

Chris Foley
  • 454
  • 3
  • 5