[Kotlin] Class / Abstract class / Example
Kotlin Class Example abstract
2023-09-14 08:59:13 时间
interface Lendable { fun borrow() } // The properties title, genre, and publicationYear can be included in the parent class because both books and DVDs // have these properties. The author and length properties however are included only in the child classes. abstract class InventoryItem(val title: String, val genre: String, var publicationYear: Int, var borrowed: Boolean) : Lendable { override fun borrow() { if (!borrowed) { borrowed = true } else { println("This item is already borrowed.") } } // If you want, you can also add a returnItem() method so that you can also un-borrow items. override fun toString(): String { return "InventoryItem(title='$title', genre='$genre', publicationYear=$publicationYear, borrowed=$borrowed)" } abstract fun copy(): InventoryItem } // A book will be not borrowed by default. // The class is called LibraryBook to prevent name clashes with previous challenges. class LibraryBook(title: String, val author: String, genre: String, publicationYear: Int) : InventoryItem(title, genre, publicationYear, false) { fun read() { println("Reading a book by $author...") } override fun copy(): InventoryItem { val copy = LibraryBook(title, author, genre, publicationYear) copy.borrowed = this.borrowed return copy } } // A DVD will also be not borrowed by default. class LibraryDVD(title: String, genre: String, val length: Int, publicationYear: Int) : InventoryItem(title, genre, publicationYear, false) { fun watch() { println("Watching $title...") } override fun copy(): InventoryItem { val copy = LibraryDVD(title, genre, length, publicationYear) copy.borrowed = this.borrowed return copy } }
相关文章
- 中国电信营业厅: 感受 Kotlin 的 "加速度"
- kotlin 之单例类详解
- 有关 Kotlin 具名参数形参传参顺序导致输出结果发生改变问题的一些探索
- 耗时半天,我用 Kotlin 实现了 helang 何语言
- kotlin 和 r8 的量子纠缠 | 类加载机制偷鸡
- 【Kotlin】Kotlin 语言集合中的高阶函数详解 ( 数据类 data class | maxBy | minBy | filter | map | any | count | find )
- 【错误记录】记录 Android 命令行执行 Java 程序中出现的错误 ( dx 打包 PC 可执行文件报错 | dalvik 命令执行 kotlin 编译的 dex 文件报错 )
- 【错误记录】Kotlin 报错 ( Some kotlin libraries attached to this project were compiled with a newer kotlin )
- 【Kotlin 协程】协程启动 ④ ( 协程启动模式 | 协程构建器启动模式参数 | DEFAULT 模式 | ATOMIC 模式 | LAZY 模式 | UNDISPATCHED 模式 )
- 【Kotlin 协程】Flow 异步流 ④ ( 流的构建器函数 | flow 构建器函数 | flowOf 构建器函数 | asFlow 构建器函数 )
- 【Kotlin 协程】Flow 异步流 ⑥ ( 调用 Flow#launchIn 函数指定流收集协程 | 通过取消流收集所在的协程取消流 )
- 【Kotlin】函数 ③ ( 匿名函数 | 匿名函数的函数类型 | 匿名函数的隐式返回 )
- 【Kotlin】扩展函数 ③ ( 定义扩展文件 | 重命名扩展函数 | Kotlin 标准库扩展函数 )