一、面向对象继承
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()...")
}
func main() {
h := Human{"zhang3","femal"}
h.Eat()
h.Walk()
}
type SuperMan struct {
Human //superman类继承了human类的方法
level int
}
//重定义父类的方法Eat()
func (this *SuperMan) Eat() {
fmt.Println("SuperMan.Eat()...")
}
//子类的新方法
func (this *SuperMan) Fly() {
fmt.Println("Superman.Fly()...")
}
s :=SuperMan{Human{"li4","female"},88}
第二种:
var s SuperMan
s.name = "lis4"
s.sex = "female"
s.level = 88
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()...")
}
//重定义父类的方法Eat()
func (this *SuperMan) Eat() {
fmt.Println("SuperMan.Eat()...")
}
//子类的新方法
func (this *SuperMan) Fly() {
fmt.Println("Superman.Fly()...")
}
type SuperMan struct {
Human //superman类继承了human类的方法
level int
}
func (this *SuperMan) Print() {
fmt.Println("name = ",this.name)
fmt.Println("sex = ",this.sex)
fmt.Println("level = ",this.level)
}
func main() {
h := Human{"zhang3","femal"}
h.Eat()
h.Walk()
//定义一个子类对象
//s :=SuperMan{Human{"li4","female"},88}
var s SuperMan
s.name = "lis4"
s.sex = "female"
s.level = 88
s.Walk() //父类的方法
s.Eat() //子类的方法
s.Fly() //子类的方法
//打印出来
s.Print()
}