简体   繁体   中英

Interface, abstract class, and the implementation

In java I often find myself implementing the List interface instead of, for example, extending the AbstractList class. This is rather common in the Java API (and in many third-party libraries I've looked at), that there exists an interface and an abstract class for that interface.

Why is this? Why is it so common that for an interface there exists an abstract class that provides a little default behaviour for it? And is there a good reason to not call an abstract class like this, say, DefaultListImpl etc. ?

Interesting question and I think many people will have many opinions. From my perspective:

  • interfaces were created to describe a contract and that should be without any implementation
    • and this changed with default methods in Java 8
  • interfaces have special place in the Java ecosystem
    • eg java.lang.reflect.Proxy only supports proxying of interfaces and not abstract classes
  • a lot of mocking frameworks does not support mocking of classes, but only mocking of interfaces
    • even if there are exceptions for this rule

So there always are reasons to use interfaces. The questions will be very similar to abstract classes vs. traits in Scala.

You proposed naming convention DefaultListImpl is not a very good idea :

  • Default does not say anything about the implementation and if we are not able to name it correctly, we either:
    • don't fully understand what we are implementing,
    • or cannot think of multiple implementations which might be a sign of overcomplicated API
  • Impl will be misleading as many people will expect full implementation of the functionality

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM