Go implementation of inheritance bits
This commit is contained in:
parent
cd6ae7f261
commit
31975286f5
55
c&s20150725/inheritance.go
Normal file
55
c&s20150725/inheritance.go
Normal file
@ -0,0 +1,55 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type Pet struct {
|
||||
Name string
|
||||
IsRunning bool
|
||||
}
|
||||
|
||||
func NewPet(name string) *Pet {
|
||||
return &Pet{Name: name}
|
||||
}
|
||||
|
||||
func (p *Pet) Run() string {
|
||||
p.IsRunning = true
|
||||
return p.Name + " is running"
|
||||
}
|
||||
|
||||
type Dog struct {
|
||||
Pet
|
||||
|
||||
currentChaseTarget *Pet
|
||||
}
|
||||
|
||||
func NewDog(name string) *Dog {
|
||||
dog := &Dog{}
|
||||
dog.Name = name
|
||||
return dog
|
||||
}
|
||||
|
||||
func (d *Dog) Chase(target *Pet) string {
|
||||
d.IsRunning = true
|
||||
d.currentChaseTarget = target
|
||||
d.currentChaseTarget.Run()
|
||||
|
||||
return d.Name + " is chasing " + target.Name
|
||||
}
|
||||
|
||||
func main() {
|
||||
cat := NewPet("Felix")
|
||||
|
||||
fmt.Printf("%#v\n", cat)
|
||||
|
||||
cat.Run()
|
||||
|
||||
fmt.Printf("%#v\n", cat)
|
||||
|
||||
dog := NewDog("Fido")
|
||||
|
||||
fmt.Printf("%#v\n", dog)
|
||||
fmt.Printf("%#v\n", dog.Chase(cat))
|
||||
|
||||
fmt.Printf("%#v\n", dog)
|
||||
fmt.Printf("%#v\n", cat)
|
||||
}
|
Loading…
Reference in New Issue
Block a user