inherit和interface

This commit is contained in:
wandoubaba 2024-11-15 16:57:45 +08:00
parent 18870edf38
commit 2e69f9483a
2 changed files with 113 additions and 0 deletions

View 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()
}

View 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)
}