Menu
CoddyTech

开放类与重写

Coddy 面向 C 开发者的 Kotlin 课程的第 39 课,共 48 课。

C 没有内置的类继承或虚方法;可以通过回调和显式状态来实现分派。Kotlin 允许通过 open 或 abstract 声明扩展类,并使用 override 标记重写。运行时分派会选择实际接收者的实现,而 super 可以复用继承的行为。如果对象不符合真正的子类型契约,优先使用组合。

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include <errno.h>
#include <limits.h>
#include <ctype.h>

struct Pass {int base;int (*cost)(const struct Pass *);};
static int discounted(const struct Pass *pass) { return pass->base-5; }
int main(void) {
struct Pass pass={12,discounted}; printf("%d\n",pass.cost(&pass));
    return 0;
}

Kotlin

open class Animal{open fun voice():String="?"};class Cat:Animal(){override fun voice():String="mew"}
fun main(){
val a:Animal=Cat()
println(a.voice())
}

移植时的陷阱

使用 open 和 override 声明预期的扩展点,不要不加区分地开放所有类。

在下面单独的练习中应用这个概念。示例使用了不同的操作或模型;请保留任务文件的 API,并实现其要求的行为。

challenge icon

挑战

简单

输入依次为非负的基础价格和不大于价格的折扣。实现 open Pass(price:Int),其中包含 open cost();再实现继承 Pass 并重写 cost()、使用 super 的 DiscountPass(price:Int,discount:Int)。依次返回基础费用和折后费用。

实现可编辑文件,并从 Exercise.solve(input: List<String>) 返回结果。不要在可编辑方法中打印内容。可见的锁定文件 Main.kt 会读取所有输入行,并在末尾添加一个换行符来打印你返回的文本。Text.kt 提供解析和格式化辅助函数。除非另有更小的范围限制,所有算术结果都在 Int 范围内。

可编辑文件:Pass.kt、DiscountPass.kt、Exercise.kt、Text.kt。只有 Main.kt 包含 main;它是锁定文件,也是最后一个文件。所有文件都在同一个包中一起编译。

锁定的驱动程序会使用新建的对象和其他协作者,独立调用所需的公共 API。请实现这些行为;仅复现测试数据的输出是不够的。

亲手试试

fun main() {
    val input = generateSequence { readlnOrNull() }.toList()
    val p:Pass=DiscountPass(12,5);check(p.cost()==7 && Pass(8).cost()==8)
    println(Exercise.solve(input))
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C 开发者的 Kotlin中的所有课

自己练习: Kotlin 在线编辑器