Skip to content

Commit 4a2c467

Browse files
authored
OOP: Polymorphism (#42)
1 parent 7189e5c commit 4a2c467

File tree

3 files changed

+58
-8
lines changed

3 files changed

+58
-8
lines changed

01-go_basic/1-5-Object-Oriented_Programming/12-接口定义.go

+7-7
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,13 @@ func (t *TeacherA) SayHello() {
2727
}
2828

2929
func main() {
30-
var student StudentE
31-
var teacher TeacherA
32-
var person Greeter
30+
var studentE StudentE
31+
var teacherA TeacherA
32+
var eachPerson Greeter
3333

34-
person = &student
35-
person.SayHello()
34+
eachPerson = &studentE
35+
eachPerson.SayHello()
3636

37-
person = &teacher
38-
person.SayHello()
37+
eachPerson = &teacherA
38+
eachPerson.SayHello()
3939
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package main
2+
3+
import "fmt"
4+
5+
// 在 Go 语言中,接口命名通常遵循一种非正式的约定,即在接口名称的末尾加上 "-er" 后缀 (Sayer)
6+
// 这种命名方式旨在描述实现该接口的对象的行为或能力
7+
8+
type Sayer interface {
9+
SayHi()
10+
}
11+
12+
type StudentF struct {
13+
id int
14+
name string
15+
}
16+
17+
type TeacherB struct {
18+
id int
19+
name string
20+
}
21+
22+
func (s *StudentF) SayHi() {
23+
fmt.Println("Hi, I'm a student.")
24+
}
25+
26+
func (t *TeacherB) SayHi() {
27+
fmt.Println("Hi, I'm a teacher.")
28+
}
29+
30+
func WhoSay(p Sayer) { // 在 Go 语言中实现多态的核心在于定义一个接口,并让不同的类型实现这个接口
31+
p.SayHi()
32+
}
33+
34+
func main() {
35+
var studentF StudentF
36+
var teacherB TeacherB
37+
38+
WhoSay(&studentF)
39+
WhoSay(&teacherB)
40+
}

01-go_basic/1-5-Object-Oriented_Programming/readme.md

+11-1
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,14 @@ func (对象 结构体类型) 方法名(参数) (返回值) {
2626

2727
## 接口
2828
- 接口就是一种规范与标准,规定了要做哪些事情,但是具体怎么做,接口是不管的
29-
- 接口把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口
29+
- 接口把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口
30+
31+
## 多态
32+
- 所谓多态,指的是多种表现形式
33+
- 多态就是同一个接口,使用不同的实例执行不同的操作
34+
35+
```go
36+
func 函数名(参数 接口类型) {
37+
38+
}
39+
```

0 commit comments

Comments
 (0)