- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 385字
- 2021-06-24 14:13:33
Abstract classes
Adding the abstract keyword in front of the class definition will mark the class as abstract. An abstract class is a partially defined class; properties and methods that have no implementation must be implemented in a derived class unless the derived class is meant to be an abstract class as well. Here is how you would define an abstract class in Kotlin:
abstract class A { abstract fun doSomething() }
Unlike interfaces, you have to mark the function as abstract if you don't provide a body definition.
You cannot create an instance of an abstract class. The role of such a class is to provide a common set of methods that multiple derived classes share. The best example of such a case is the InputStream class. This will be very familiar to a developer who has already worked with Java. The JDK Documentation says:
If you look at the java.io package, you will find a few implementations for it—AudioInputStream, ByteArrayInputStream, FileInputStream, and many more. You could also provide an implementation of it.
You can inherit an A class with a function flagged as opened for being redefined (overridable, as we will see shortly) and marked as abstract in the derived class. This way, the derived class will become abstract. Any class that inherits from the derived class will need to provide an implementation, and it won't be able to access the implementation defined in the A class:
open class AParent protected constructor() { open fun someMethod(): Int = Random().nextInt() } abstract class DDerived : AParent() { abstract override fun someMethod(): Int } class AlwaysOne : DDerived() { override fun someMethod(): Int { return 1 } }
The example is pretty straightforward. We have a parent class that defines someMethod, returning a random integer. A DDerived class inherits this class (please note we have to invoke the empty constructor on the parent class) and marks the method as abstract. Then, our AlwaysOne class will have to provide a function body for our method that always returns 1.
- Oracle WebLogic Server 12c:First Look
- PaaS程序設計
- Java編程指南:基礎知識、類庫應用及案例設計
- INSTANT Weka How-to
- C語言程序設計案例式教程
- HTML5+CSS3+JavaScript Web開發案例教程(在線實訓版)
- Oracle Database 12c Security Cookbook
- C程序設計案例教程
- Python機器學習基礎教程
- MySQL從入門到精通(軟件開發視頻大講堂)
- Spring Security Essentials
- Applied Deep Learning with Python
- Python應用開發技術
- Python數據可視化之matplotlib實踐
- RESTful Web API Design with Node.js(Second Edition)