一、面向对象继承
- 写一个父类
package mainimport "fmt"type Human struct {name stringsex 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 SuperMans.name = "lis4"s.sex = "female"s.level = 88
- 子类继承父类的使用
package mainimport "fmt"type Human struct {name stringsex 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 SuperMans.name = "lis4"s.sex = "female"s.level = 88s.Walk() //父类的方法s.Eat() //子类的方法s.Fly() //子类的方法//打印出来s.Print()}