Interface vs Base class

后端 未结 30 2532
甜味超标
甜味超标 2020-11-21 07:34

When should I use an interface and when should I use a base class?

Should it always be an interface if I don\'t want to actually define a base implementation of the

30条回答
  •  无人共我
    2020-11-21 07:44

    Prefer interfaces over abstract classes

    Rationale, the main points to consider [two already mentioned here] are :

    • Interfaces are more flexible, because a class can implement multiple interfaces. Since Java does not have multiple inheritance, using abstract classes prevents your users from using any other class hierarchy. In general, prefer interfaces when there are no default implementations or state. Java collections offer good examples of this (Map, Set, etc.).
    • Abstract classes have the advantage of allowing better forward compatibility. Once clients use an interface, you cannot change it; if they use an abstract class, you can still add behavior without breaking existing code. If compatibility is a concern, consider using abstract classes.
    • Even if you do have default implementations or internal state, consider offering an interface and an abstract implementation of it. This will assist clients, but still allow them greater freedom if desired [1].
      Of course, the subject has been discussed at length elsewhere [2,3].

    [1] It adds more code, of course, but if brevity is your primary concern, you probably should have avoided Java in the first place!

    [2] Joshua Bloch, Effective Java, items 16-18.

    [3] http://www.codeproject.com/KB/ar...

提交回复
热议问题