3

Generally we use code to interface :

List<String> list  = new ArrayList<String>();

Can we write the following?

AbstractList<String> list  = new ArrayList<String>();

What will be the disadvantage of this particular initialization? Any insights will be appreciated.

Eran
  • 387,369
  • 54
  • 702
  • 768
Niche
  • 142
  • 1
  • 2
  • 9
  • Before doing things like this, your should look into the possible issues with covariance and contravariance (e.g. http://stackoverflow.com/questions/2501023/demonstrate-covariance-and-contravariance-in-java) – realbart Oct 14 '14 at 11:14

4 Answers4

5

Defining the list to be an AbstractList would tie your implementation to sub-classes of AbstractList, while using the List interface allows you to assign to the list variable arbitrary implementations of that interface.

Defining the list as AbstractList will also give you access (with no need for casting) to the methods of AbstractList which are not part of the List interface, but using them would make your code less flexible.

If you don't have a very good reason to do it, don't do it.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

The main disadvantage is the general one: in Java, you can only inherit from one class at a time, while you can implement as many interfaces as you like.

If list is a private or local variable, there's virtually no advantage initializing as an interface. You'd be better of with

ArrayList<String> list  = new ArrayList<String>();

However, if you have a public field or a method parameter, you'd be better off with the least specific declaration: the interface. The abstract class also implements the interface, so it can be used. But the consumer of your class can then use any class that implements the interface, while this class can inherit from any other class they might like.

realbart
  • 3,497
  • 1
  • 25
  • 37
1

The advantage of using List<String> over AbstractList<String> is that List specifies a contract, and AbstractList specifies a (partial) implementation. Using List ensures that your code is compatible with any implementation of List, rather than just those derived from AbstractList.

While following this practice might not seem like that big a deal with it comes to variable declarations, following this usage through out your code ensure greater flexibility throughout your application.

PeterK
  • 1,697
  • 10
  • 20
0

One disadvantage of using AbstractList like that is that you are limiting yourself to using list classes that extend AbstractList. It is quite possible to implement the List interface without having AbstractList as a superclass.

A second disadvantage is that this won't compile:

List<String> list = new ArrayList<String>();

AbstractList<String> list2 = list;

The Java type system won't let you assume that every List<String> is an AbstractList<String>.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216