Below is the diagram, where, if we just consider the implementations of List,
AbstractList
maintains the core behavior of list. To introduce the new implementationclass MyList
(say) one can inheritAbstractList
and override(if necessary) required methods. By extendingAbstractList
. Additionally,class MyList
is obeying the contract to behave like a list.class MyList extends AbstractList{..}
Users can use collection hierarchy, as,
AbstractList l = new ArrayList<String>(); l.add("one"); //execute ArrayList's add method
A class can also maintain composition relation with any list implementation(at runtime), by having
AbstractList l;
as member, that gets populated at runtime, with any list implementation.
So,
I would like to understand the clear reason, Why additionally interface List<E>
is introduced?
note1: Intention is to understand, how to use interface. This not a duplicate question, because both abstract class and interface are used.I did not use the word 'instead of' or 'rather'
note2: Let us not get into java-8 default methods, as above collection hierarchy was designed with whatever was provided till java-7
class Book extends Content implements List<Page>
- one couldn't do this with AbstractList, because there would be no way for Book to extend both Content and AbstractList simultaneouslyAbstractList
documentation. Quote: "This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array)."List
is purely a specification of interface,AbstractList
has behaviour that could conceivably be wrong in some situations. Interface-only inheritance should be preferred when you do not need to inherit behaviour but only need to provide the capability of polymorphism.class MyList
that defines all of the required methods and obeys the general contract is preferred to implement aninterface List
, because theclass Myclass
(some business class) do not need to reside in the above class hierarchy. This has nothing to do with multiple inheritance or polymorphism.