1. 概述

本文将介绍如何在 Kotlin 中同时继承一个类并实现多个接口。这在 Java 中通过 extendsimplements 关键字完成,但在 Kotlin 中语法不同。我们将通过具体示例来演示这一过程。

2. 问题背景

在 Java 中,我们使用 extends 来继承类,使用 implements 来实现接口。但在 Kotlin 中,这两种操作都通过冒号 : 来统一表示。

如果你是从 Java 转向 Kotlin 的开发者,这点可能一开始不太习惯。我们来看一个例子。

我们有如下一个 Person 类和两个接口:

open class Person(private val firstName: String, private val lastName: String, val age: Int) {
    fun fullName(): String {
        return "$firstName $lastName"
    }
}

interface BaeldungReader {
    fun readArticles(): String
}

interface BaeldungAuthor {
    fun writeArticles(): String
}
  • Person 是一个可以被继承的类,因为它被标记为 open
  • BaeldungReaderBaeldungAuthor 是两个接口,分别定义了一个方法

我们的目标是创建一个 Person 的子类,并同时实现这两个接口。

3. Kotlin 中的类继承与接口实现

Kotlin 使用冒号 : 来表示继承与接口实现:

  • class MyType : SuperType 表示继承
  • class MyType : Interface1, Interface2 表示实现多个接口
  • class MyType : SuperType, Interface1, Interface2 则表示同时继承类并实现多个接口

注意

  • 冒号后可以同时写父类和接口,用逗号 , 分隔
  • 父类和接口的顺序 不影响编译结果
  • Kotlin 中重写方法必须使用 override 关键字,而不是 Java 中的 @Override 注解

示例:创建 Developer 类

class Developer(firstName: String, lastName: String, age: Int, private val skills: Set<String>) 
  : Person(firstName, lastName, age), BaeldungAuthor, BaeldungReader {
    override fun readArticles(): String {
        return "${fullName()} enjoys reading articles in these categories: $skills"
    }

    override fun writeArticles(): String {
        return "${fullName()} writes articles in these categories: $skills"
    }
}

该类:

  • 继承了 Person
  • 实现了 BaeldungReaderBaeldungAuthor 接口
  • 重写了两个接口的方法

单元测试验证

我们可以通过单元测试验证其行为是否符合预期:

val developer: Developer = Developer("James", "Bond", 42, setOf("Kotlin", "Java", "Linux"))
developer.apply {
    assertThat(this).isInstanceOf(Person::class.java).isInstanceOf(BaeldungReader::class.java).isInstanceOf(BaeldungAuthor::class.java)
    assertThat(fullName()).isEqualTo("James Bond")
    assertThat(readArticles()).isEqualTo("James Bond enjoys reading articles in these categories: [Kotlin, Java, Linux]")
    assertThat(writeArticles()).isEqualTo("James Bond writes articles in these categories: [Kotlin, Java, Linux]")
}

该测试验证了:

  • developerPerson 的实例
  • 同时实现了两个接口
  • 重写的方法返回了正确的字符串

⚠️ 踩坑提醒:在 Kotlin 中,如果你忘记 override 关键字,编译器会报错,而不是像 Java 一样通过注解检查。所以一定要注意语法差异。

4. 小结

本文介绍了 Kotlin 中如何同时继承类和实现多个接口。Kotlin 使用统一的冒号语法 :,将父类和接口放在一起声明,语法简洁但语义清晰。

主要知识点总结如下:

操作 Kotlin 语法
继承类 class SubClass : SuperClass(...)
实现接口 class MyClass : Interface1, Interface2
同时继承与实现 class MyClass : SuperClass(...), Interface1, Interface2
方法重写 使用 override 关键字

完整代码示例可在 GitHub 仓库 获取。



原始标题:Extending a Class and Implementing Interfaces at the Same Time in Kotlin