官术网_书友最值得收藏!

Interface or abstract classes

There is always a debate over using either an interface or an abstract class. The following are a few rules to follow when deciding which way to go:

  • Is-A versus Can-Do: Any type can inherit from one parent class only and multiple interfaces. If for the derived class B you can't say B Is-an A (A is the base type), contradictory. Interfaces imply a Can-Do relationship. If the Can-Do functionality is applicable to different object types, go with an interface implementation. For example, for both FileOutputStream and ByteOutputpuStream (and any of the other sibling implementations available), you can say they have an Is-A relationship with java.io.OutputStream. Hence, you will see that OutputStream is an abstract class providing common implementations to all objects that represent a writable stream. However, Autocloseable , which represents an object holding a resource that can be released when the close method is invoked, provides a Can-do functionality and thus it makes sense to have it as an interface.
  • Promote code reuse: I am sure you will agree it is easier to inherit a class rather than an interface, where you have to provide an implementation for all the methods defined. A parent class can provide a lot of common functionality; thus, the derived class has only to  redefine or implement a small subset of the methods defined.
  • Versioning: If you work with an interface and you add a new member to it, you force all the derived classes to change their code by adding the new implementation. The source code has to be changed and recompiled. The same is not applicable to an abstract class. You can add your new method and make use of it, and the user source code doesn't even need to be recompiled.
主站蜘蛛池模板: 顺平县| 长沙市| 肇庆市| 锡林浩特市| 株洲市| 福鼎市| 宝丰县| 永顺县| 饶河县| 普兰店市| 南靖县| 醴陵市| 平潭县| 灵璧县| 台州市| 乌什县| 宜宾市| 二连浩特市| 正宁县| 沾化县| 成安县| 遵义市| 桦南县| 玛曲县| 建平县| 若羌县| 宝应县| 饶河县| 古丈县| 福贡县| 眉山市| 河北区| 上饶县| 石河子市| 忻城县| 西乡县| 哈尔滨市| 隆德县| 微博| 柳林县| 临沭县|