All Collections implements interface Collection, these collection have specific abstract hierarchy e.g.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With