go 中的面向物件用法
阿新 • • 發佈:2019-01-24
package main
//實現繼承,封裝,這裡沒有演示多型用法
import "fmt"
type Parent struct{ Name string Age int Address string Sex int } type Child struct{ Parent //通過包含實現繼承 Work string } type IParent interface{ Say() Walk() } type IChild interface{ DoWork() Happy() } /** *定義父類中的方法 */ func (p *Parent) Say(){ fmt.Println("呼叫父類的Say()方法")} func (p *Parent) Walk(){ fmt.Println("呼叫父類的Walk()方法")} /** *定義子類中的方法 */ func (c *Child) DoWork(){fmt.Println("呼叫子類的DoWork()方法")} func (c *Child) Happy(){fmt.Println("呼叫子類的DoWork()方法")} /** *實現set,get方法 *定義接收者為指標型別,由於程式碼少就寫成一行了 */ func (ch *Child) setName(name string){ch.Name = name} func (ch *Child) getName() string{ return ch.Name} func (ch *Child) setAge(age int){ch.Age = age} func (ch *Child) getAge()int{ return ch.Age } func (ch *Child) setAddress(address string){ch.Address = address} func (ch *Child) getAddress()string{ return ch.Address } func (ch *Child) setSex(sex int){ ch.Sex = sex } func (ch *Child) getSex() int{ return ch.Sex} func (ch *Child) setWork(work string){ ch.Work = work} func (ch *Child) getWork() string {return ch.Work} func main(){ fmt.Println("測試物件方法") child := Child{Parent:Parent{Name:"Jackm",Age:23,Address:"gdsz",Sex:1},Work:"IT"} fmt.Println(child) ch := Child{} ch.setName("mfz");ch.setAge(24) ch.setAddress("gdsz");ch.setSex(1) ch.setWork("id-dev") ch.Say(); ch.Walk() ch.DoWork(); ch.Happy() fmt.Println("Name:",ch.getName(),"Age:",ch.getAge(),"Address:",ch.getAddress(),"Sex:",ch.getSex(),"Work:",ch.getWork()) }