Kotlin 接口 #
一、接口定义 #
1.1 基本语法 #
kotlin
interface Clickable {
fun click()
}
1.2 实现接口 #
kotlin
class Button : Clickable {
override fun click() {
println("Button clicked")
}
}
val button = Button()
button.click()
1.3 实现多个接口 #
kotlin
interface Clickable {
fun click()
}
interface Focusable {
fun focus()
}
class Button : Clickable, Focusable {
override fun click() {
println("Clicked")
}
override fun focus() {
println("Focused")
}
}
二、接口方法 #
2.1 抽象方法 #
kotlin
interface Drawable {
fun draw() // 抽象方法,没有方法体
}
class Circle : Drawable {
override fun draw() {
println("Drawing circle")
}
}
2.2 默认方法 #
kotlin
interface Clickable {
fun click()
fun doubleClick() {
click()
click()
}
}
class Button : Clickable {
override fun click() {
println("Clicked")
}
// doubleClick 使用默认实现
}
val button = Button()
button.doubleClick() // Clicked Clicked
2.3 重写默认方法 #
kotlin
interface Clickable {
fun click()
fun doubleClick() {
click()
click()
}
}
class SpecialButton : Clickable {
override fun click() {
println("Clicked")
}
override fun doubleClick() {
println("Special double click")
}
}
三、接口属性 #
3.1 抽象属性 #
kotlin
interface Vehicle {
val speed: Int // 抽象属性
}
class Car : Vehicle {
override val speed: Int = 100
}
3.2 带访问器的属性 #
kotlin
interface Vehicle {
val speed: Int
val maxSpeed: Int
get() = 200
}
class Car : Vehicle {
override val speed: Int = 100
// maxSpeed 使用默认实现
}
3.3 在构造函数中实现 #
kotlin
interface Vehicle {
val speed: Int
}
class Car(override val speed: Int) : Vehicle
四、接口继承 #
4.1 接口继承接口 #
kotlin
interface Clickable {
fun click()
}
interface DoubleClickable : Clickable {
fun doubleClick()
}
class Button : DoubleClickable {
override fun click() {
println("Clicked")
}
override fun doubleClick() {
println("Double clicked")
}
}
4.2 组合接口 #
kotlin
interface Readable {
fun read(): String
}
interface Writable {
fun write(data: String)
}
interface Storage : Readable, Writable {
fun clear()
}
五、解决冲突 #
5.1 方法冲突 #
kotlin
interface A {
fun foo() { println("A") }
fun bar()
}
interface B {
fun foo() { println("B") }
fun bar() { println("B bar") }
}
class C : A, B {
override fun foo() {
super<A>.foo()
super<B>.foo()
}
override fun bar() {
super<B>.bar()
}
}
5.2 钻石问题 #
kotlin
interface Base {
fun message(): String
}
interface A : Base {
override fun message() = "A"
}
interface B : Base {
override fun message() = "B"
}
class C : A, B {
override fun message(): String {
return super<A>.message() // 选择 A 的实现
}
}
六、函数式接口 #
6.1 SAM 接口 #
kotlin
fun interface ClickListener {
fun onClick()
}
// 使用 Lambda
val listener = ClickListener { println("Clicked") }
listener.onClick()
6.2 实际应用 #
kotlin
fun interface Predicate<T> {
fun test(value: T): Boolean
}
val isEven = Predicate<Int> { it % 2 == 0 }
isEven.test(4) // true
七、接口 vs 抽象类 #
7.1 主要区别 #
| 特性 | 接口 | 抽象类 |
|---|---|---|
| 状态 | 不能存储状态 | 可以存储状态 |
| 构造函数 | 没有 | 可以有 |
| 多继承 | 支持多实现 | 单继承 |
| 成员 | 抽象方法、默认方法 | 抽象方法、具体方法、属性 |
7.2 选择建议 #
kotlin
// 使用接口:定义行为
interface Clickable {
fun click()
}
// 使用抽象类:共享实现
abstract class BaseAdapter {
protected val items = mutableListOf<Any>()
abstract fun bind(holder: ViewHolder, position: Int)
fun getItemCount() = items.size
}
八、实战示例 #
8.1 观察者模式 #
kotlin
interface Observer<T> {
fun onUpdate(data: T)
}
interface Observable<T> {
fun subscribe(observer: Observer<T>)
fun unsubscribe(observer: Observer<T>)
fun notifyObservers(data: T)
}
class NewsAgency : Observable<String> {
private val observers = mutableListOf<Observer<String>>()
override fun subscribe(observer: Observer<String>) {
observers.add(observer)
}
override fun unsubscribe(observer: Observer<String>) {
observers.remove(observer)
}
override fun notifyObservers(data: String) {
observers.forEach { it.onUpdate(data) }
}
fun publish(news: String) {
notifyObservers(news)
}
}
class NewsReader(val name: String) : Observer<String> {
override fun onUpdate(data: String) {
println("$name received: $data")
}
}
8.2 策略模式 #
kotlin
interface PaymentStrategy {
fun pay(amount: Double)
}
class CreditCardPayment : PaymentStrategy {
override fun pay(amount: Double) {
println("Paid $amount by credit card")
}
}
class PayPalPayment : PaymentStrategy {
override fun pay(amount: Double) {
println("Paid $amount by PayPal")
}
}
class ShoppingCart {
private var strategy: PaymentStrategy? = null
fun setPaymentStrategy(strategy: PaymentStrategy) {
this.strategy = strategy
}
fun checkout(amount: Double) {
strategy?.pay(amount) ?: println("No payment method selected")
}
}
8.3 回调接口 #
kotlin
interface Callback<T> {
fun onSuccess(result: T)
fun onError(error: Exception)
}
fun fetchData(callback: Callback<String>) {
try {
val data = "Data from server"
callback.onSuccess(data)
} catch (e: Exception) {
callback.onError(e)
}
}
fetchData(object : Callback<String> {
override fun onSuccess(result: String) {
println("Success: $result")
}
override fun onError(error: Exception) {
println("Error: ${error.message}")
}
})
九、最佳实践 #
9.1 接口命名 #
kotlin
// 推荐:形容词或名词
interface Clickable
interface Drawable
interface Repository
// 不推荐:动词
// interface Click
// interface Draw
9.2 单一职责 #
kotlin
// 推荐:职责单一
interface Readable {
fun read(): String
}
interface Writable {
fun write(data: String)
}
// 不推荐:职责过多
// interface Storage {
// fun read(): String
// fun write(data: String)
// fun delete()
// fun compress()
// }
9.3 使用函数式接口 #
kotlin
// 推荐:单方法接口使用 fun interface
fun interface OnClickListener {
fun onClick()
}
// 使用 Lambda 简化
button.setOnClickListener { println("Clicked") }
十、总结 #
接口要点:
| 特性 | 说明 |
|---|---|
| 抽象方法 | 没有方法体 |
| 默认方法 | 有方法体 |
| 抽象属性 | 需要实现 |
| 多实现 | 实现多个接口 |
| SAM | 函数式接口 |
下一步,让我们学习 数据类!
最后更新:2026-03-27