- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 301字
- 2021-06-24 14:13:33
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.
推薦閱讀
- Dynamics 365 for Finance and Operations Development Cookbook(Fourth Edition)
- Testing with JUnit
- Building Modern Web Applications Using Angular
- R語言經(jīng)典實(shí)例(原書第2版)
- Learning Selenium Testing Tools with Python
- Vue.js 3.x從入門到精通(視頻教學(xué)版)
- 零基礎(chǔ)入門學(xué)習(xí)Python(第2版)
- 微服務(wù)從小白到專家:Spring Cloud和Kubernetes實(shí)戰(zhàn)
- Hands-On Nuxt.js Web Development
- Kotlin Programming By Example
- Java 9 Programming By Example
- Oracle 12c從入門到精通(視頻教學(xué)超值版)
- 關(guān)系數(shù)據(jù)庫與SQL Server 2012(第3版)
- 精益軟件開發(fā)管理之道
- React.js實(shí)戰(zhàn)