inherit和interface
This commit is contained in:
parent
18870edf38
commit
2e69f9483a
51
bilibili/aceid/struct/inherit/test.go
Normal file
51
bilibili/aceid/struct/inherit/test.go
Normal file
@ -0,0 +1,51 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type Human struct {
|
||||
name string
|
||||
sex string
|
||||
}
|
||||
|
||||
func (this *Human) Eat() {
|
||||
fmt.Println("Human.Eat()...")
|
||||
}
|
||||
|
||||
func (this *Human) Walk() {
|
||||
fmt.Println("Human.Walk()...")
|
||||
}
|
||||
|
||||
type Superman struct {
|
||||
Human
|
||||
level int
|
||||
}
|
||||
|
||||
func (this *Superman) Eat() {
|
||||
fmt.Println("Superman.Eat()...")
|
||||
}
|
||||
|
||||
func (this *Superman) Fly() {
|
||||
fmt.Println("Superman.Fly()...")
|
||||
}
|
||||
|
||||
func (this *Superman) Show() {
|
||||
fmt.Println("name = ", this.name)
|
||||
fmt.Println("sex = ", this.sex)
|
||||
fmt.Println("level = ", this.level)
|
||||
}
|
||||
|
||||
func main() {
|
||||
h := Human{"zhang3", "female"}
|
||||
h.Eat()
|
||||
h.Walk()
|
||||
|
||||
var s Superman
|
||||
s.name = "li4"
|
||||
s.sex = "male"
|
||||
s.level = 96
|
||||
// s := Superman{Human{"li4", "female"}, 88}
|
||||
s.Walk() // 父类方法(子类没有重载)
|
||||
s.Eat() // 子类方法
|
||||
s.Fly() // 子类方法
|
||||
s.Show()
|
||||
}
|
62
bilibili/aceid/struct/interface/test.go
Normal file
62
bilibili/aceid/struct/interface/test.go
Normal file
@ -0,0 +1,62 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// 本质是一个指针
|
||||
type AnimalIF interface {
|
||||
Sleep()
|
||||
GetColor() string // 获取颜色
|
||||
GetType() string // 获取种类
|
||||
}
|
||||
|
||||
// 定义具体的类
|
||||
type Cat struct {
|
||||
color string // 颜色
|
||||
}
|
||||
|
||||
func (this *Cat) Sleep() {
|
||||
fmt.Println("Cat is sleep")
|
||||
}
|
||||
|
||||
func (this *Cat) GetColor() string {
|
||||
return this.color
|
||||
}
|
||||
|
||||
func (this *Cat) GetType() string {
|
||||
return "Cat"
|
||||
}
|
||||
|
||||
type Dog struct {
|
||||
color string
|
||||
}
|
||||
|
||||
func (this *Dog) Sleep() {
|
||||
fmt.Println("Dog is sleep")
|
||||
}
|
||||
|
||||
func (this *Dog) GetColor() string {
|
||||
return this.color
|
||||
}
|
||||
|
||||
func (this *Dog) GetType() string {
|
||||
return "Dog"
|
||||
}
|
||||
|
||||
func showAnimal(animal AnimalIF) {
|
||||
animal.Sleep()
|
||||
fmt.Println("color = ", animal.GetColor())
|
||||
fmt.Println("type = ", animal.GetType())
|
||||
}
|
||||
|
||||
func main() {
|
||||
var animal AnimalIF // 接口数据类型(父类指针)
|
||||
animal = &Cat{"green"}
|
||||
animal.Sleep()
|
||||
animal = &Dog{"yellow"}
|
||||
animal.Sleep()
|
||||
|
||||
cat := Cat{"gray"}
|
||||
dog := Dog{"black"}
|
||||
showAnimal(&cat)
|
||||
showAnimal(&dog)
|
||||
}
|
Loading…
Reference in New Issue
Block a user