Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Collections: Interfaces and Abstract classes

All Collections implements interface Collection, these collection have specific abstract hierarchy e.g.

  • AbstractCollection -> AbstractList -> ArrayList
  • AbstractCollection -> AbstractSet -> HashSet

But there are also corresponding interfaces like Collection, List, Set. These interface seem to me kind of redundant.

Why are they here ? Is is just convention or is there a reason to just implement interface and not extend the abstract class.

like image 863
jellyfication Avatar asked Dec 05 '25 17:12

jellyfication


2 Answers

The interfaces are there because it's good to be able to assign a type to a variable or parameter without imposing an implementation.

For instance if I create a persistent entity to use in Hibernate, and it has a collection of things, I want to assign a type of List or Set to that. Hibernate will swap out whatever list I initialize it to with its own, with some Hibernate-specific implementation that does lazy-loading or whatever else it needs to. The Hibernate developers may not want to be constrained by having to extend the abstract class.

The abstract class exists as a convenience for implementers. The interface is a contract used by clients.

like image 101
Nathan Hughes Avatar answered Dec 08 '25 05:12

Nathan Hughes


Implementing an interface is much different from extending an abstract class.

Let's suppose that class Animal is an abstract class, and that Dog, Cat, Snake and Shark extend Animal.

The default Animal.move() implementation simply moves them.

But, interfaces allow us to further group-out similar animals, such as RunningAnimal, SwimmingAnimal.

So, if Dog extends Animal implements RunningAnimal, along the inherited move() he will also have to implement his own run(), which might find it's way in the overridden move() inherited from Animal. Does this make sense to you yet or do I need to clarify better / with some code? :)

Interfaces let you group similar functionality of different classes. "Clickable", "Sortable", "Serializable" ... They all encompass the members thru a shared functionality (so a list of clickables is more than a list of buttons) rather than a same purpose.

So, think about it like this

Cat extends Animal implements RunningAnimal, ClimbingAnimal  -- inherits move() has to implement run() and climbTree()
Dog extends Animal implements RunningAnimal  -- inherits move(), has to implement run()
Snake extends Animal                         -- likely overrides inherited move()
Shark extends Animal implements SwimmingAnimal -- likely overrides move(), has to implement swim()
like image 30
Shark Avatar answered Dec 08 '25 05:12

Shark