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"}
120 次點擊