Search code examples
javajava-8interfaceabstract-class

Are there any examples of abstract class vs interface use in the java standard libraries from jdk-8 on forward?


For example, in the java tutorials (https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html), the AbstractMap class is used as an example for an abstract class. Since jdk8, where interface methods can now be default or static, is there any reason (other than the fact that it's already there and previously made sense) that AbstractMap couldn't have been an interface? As far as I understand, the remaining differences post jdk8 are:

  1. An abstract class can be used to abstract state (not constrained to static final fields/ and have can have constructors) where an interface can not.
  2. Multiple interfaces can be implemented (by related or unrelated classes) while only one class can be extended.
  3. The added functionality to interface was to preserve backwards compatibility.

It looks like if done from scratch, an interface would have provided largely the same functionality in most cases, and deciding on which to use boils down to points 1 and 2 regardless of 3 being the reason for the expanded interface functionality.

Is there anything I'm missing? Are there any examples of standard library classes made at or post jdk8 that exemplify these differences? I'm learning so please forgive me if I've overlooked something.


Solution

  • One point missing from the list is protected methods. An interface can only have public ones. So, if you have a template method pattern, where you want the subclasses to implements something, but not expose it as a public API, you can't do that with an interface.

    An example could be AbstractList#removeRange(int, int). Also an example of no.1 from your list (has a protected field).

    Now, to why particularily the AbstractMap is not an interface in the new APIs, I can't speak for JDK developers. One thing is the java.util collections share a similar design and changing one but not the others would break consistency. Some backwards compatibility too. Even if personally I wouldn't probably depend on the fact that something is a class rather than an interface.