package main
//继承
import (
"fmt"
)
//人类接口
type Human interface{
OneDay()
Work() *Remuneration
}
//报酬
type Remuneration struct{
//钱
Money int
//食物
Food string
//爵 位
Title string
}
//人类
type People struct{
}
func (s *People) Eat(){
println("people eat foot")
}
func (s *People) Drink(){
println("people drink water")
}
////某一天的活动,继承人类接口
//func (s *People) OneDay(){
// s.Eat()
// s.Drink()
//}
//富人
type RichPerson struct{
People
Age uint32
}
//穷人
type PoorPerson struct{
People
Age uint32
}
//贵族
type NoblePerson struct{
People
Age uint32
}
func (s *RichPerson) Drink(){
println("WangWu drink Orange Juice")
}
func (s *NoblePerson) Drink(){
println("WangWu drink wine")
}
func (s *People) Work() *Remuneration {
return &Remuneration{100,"",""}
}
func (s *PoorPerson) Work() *Remuneration {
return &Remuneration{0,"bread",""}
}
func (s *NoblePerson) Work() *Remuneration {
return &Remuneration{1000,"","may be"}
}
////某一天的活动,继承人类接口
//func (s *People) OneDay() {
// s.Eat()
// s.Drink()
//
// println(fmt.Sprintf("%#v", s.Work()))
//}
//富人RichPerson实现了human接口
func (s *RichPerson) OneDay() {
s.Eat()
s.Drink()
println(fmt.Sprintf("%#v", s.Work()))
}
//穷人PoorPerson实现了human接口
func (s *PoorPerson) OneDay() {
s.Eat()
s.Drink()
println(fmt.Sprintf("%#v", s.Work()))
}
//贵族RichPerson实现了human接口
func (s *NoblePerson) OneDay() {
s.Eat()
s.Drink()
println(fmt.Sprintf("%#v", s.Work()))
}
func main() {
zhangSan := PoorPerson{Age:25}
liSi := RichPerson{Age:26}
wangWu := NoblePerson{Age:27}
zhangSan.OneDay()
liSi.OneDay()
wangWu.OneDay()
println("----------上面的结果和下面的结果一样------------")
var h1 Human = &zhangSan
var h2 Human = &liSi
var h3 Human = &wangWu
polymorphism(h1)
polymorphism(h2)
polymorphism(h3)
}
//多态
func polymorphism(s Human) {
s.OneDay()
}
运行结果:
people eat foot
people drink water
&main.Remuneration{Money:0, Food:"bread", Title:""}
people eat foot
WangWu drink Orange Juice
&main.Remuneration{Money:100, Food:"", Title:""}
people eat foot
WangWu drink wine
&main.Remuneration{Money:1000, Food:"", Title:"may be"}
----------上面的结果和下面的结果一样------------
people eat foot
people drink water
&main.Remuneration{Money:0, Food:"bread", Title:""}
people eat foot
WangWu drink Orange Juice
&main.Remuneration{Money:100, Food:"", Title:""}
people eat foot
WangWu drink wine
&main.Remuneration{Money:1000, Food:"", Title:"may be"}
有疑问加站长微信联系(非本文作者)