Skip to content

Commit aaf881e

Browse files
committed
Update Interfaces.md
1 parent 77c17bd commit aaf881e

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

ClassesAndObjects/Interfaces.md

+9-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
## 接口
22
Kotlin 的接口很像 java 8。它们都可以包含抽象方法,以及方法的实现。和抽象类不同的是,接口不能保存状态。可以有属性但必须是抽象的,或者提供访问器的实现。
33

4-
接口用关键字 interface 来定义:
4+
接口用关键字 `interface` 来定义:
55

66
```kotlin
77
interface MyInterface {
@@ -12,7 +12,7 @@ interface MyInterface {
1212
}
1313
```
1414

15-
### 接口的实现
15+
### 实现接口
1616
一个类或对象可以实现一个或多个接口
1717

1818
```kotlin
@@ -29,16 +29,16 @@ class Child : MyInterface {
2929
```kotlin
3030
interface MyInterface {
3131
val property: Int // abstract
32-
32+
3333
val propertyWithImplementation: String
3434
get() = "foo"
3535

36-
fun foo() {
36+
fun foo() {
3737
print(property)
38-
}
38+
}
3939
}
4040

41-
class Child : MyInterface {
41+
class Child : MyInterface {
4242
override val property: Int = 29
4343
}
4444
```
@@ -73,4 +73,6 @@ class D : A, B {
7373
}
7474
```
7575

76-
A B 接口都有声明了 foo() bar() 函数。它们都实现了 foo() 方法,但只有 B 实现了 bar() ,bar() 在 A 中并没有声明它是抽象的,这是因为在接口中如果函数没有函数体,那么默认是抽像的。现在,如果我们从 A 中派生一个 C 实体类,显然我们需要重写 bar() ,并实现它。而我们从 A 和 B 派生一个 D ,我们不用重写 bar() 方法,因为我们的一个继承中有一个已经实现了它。但我们继承了两个 foo() 的实现,因此编译器不知道应该选哪个,并强制我们重写 foo() 并且明确指出我们想怎么实现。
76+
A B 接口都有声明了 foo() 和 bar() 函数。它们都实现了 foo() 方法,但只有 B 实现了 bar() ,bar() 在 A 中并没有声明它是抽象的,这是因为在接口中如果函数没有函数体,那么默认是抽像的。
77+
78+
不过,如果我们从 A 中派生一个 C 实体类,显然我们需要重写 bar() ,并实现它。而我们从 A 和 B 派生一个 D ,我们不用重写 bar() 方法,因为我们的一个继承中有一个已经实现了它。但我们继承了两个 foo() 的实现,因此编译器不知道应该选哪个,并强制我们重写 foo() 并且明确指出我们想怎么实现。

0 commit comments

Comments
 (0)