Item 20: Prefer interfaces to abstract classes

Advantages

  • Existing classes can easily be reconstructed to implement a new interface. You just need to use implements clause to the class declaration and add the required methods
  • Interfaces are ideal for defining mixins (Example: http://hannesdorfmann.com/android/java-mixins)
  • Interfaces allow for the construction of non-hierarchical type frameworks. They are great for organizing things that don’t fall into a hierarchy
  • Interfaces enable safe, powerful functionality enhancements via the wrapper class idiom (Item 18). If you use abstract classes, a programmer should use the inheritance. The resulting classes are less powerful and more fragile

Skeletal implementation class

You can combine the advantages of interfaces and abstract classes using Skeletal implementation class. You can check the following links for more information:

https://dzone.com/articles/favour-skeletal-interface-in-javahttp://javaonfly.blogspot.com/2016/09/favaor-skeletal-implementation-in-java.html
https://stackoverflow.com/questions/13436995/why-and-when-to-use-skeletal-implementation-in-java

Leave a Reply

Your email address will not be published. Required fields are marked *