mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 02:16:48 +08:00
update book code
This commit is contained in:
59
eBook/exercises/chapter_10/inheritance_car.go
Executable file
59
eBook/exercises/chapter_10/inheritance_car.go
Executable file
@@ -0,0 +1,59 @@
|
||||
// inheritance_car.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Engine interface {
|
||||
Start()
|
||||
Stop()
|
||||
}
|
||||
|
||||
type Car struct {
|
||||
wheelCount int
|
||||
Engine
|
||||
}
|
||||
|
||||
// define a behavior for Car
|
||||
func (car Car) numberOfWheels() int {
|
||||
return car.wheelCount
|
||||
}
|
||||
|
||||
type Mercedes struct {
|
||||
Car //anonymous field Car
|
||||
}
|
||||
|
||||
// a behavior only available for the Mercedes
|
||||
func (m *Mercedes) sayHiToMerkel() {
|
||||
fmt.Println("Hi Angela!")
|
||||
}
|
||||
|
||||
func (c *Car) Start() {
|
||||
fmt.Println("Car is started")
|
||||
}
|
||||
|
||||
func (c *Car) Stop() {
|
||||
fmt.Println("Car is stopped")
|
||||
}
|
||||
|
||||
func (c *Car) GoToWorkIn() {
|
||||
// get in car
|
||||
c.Start();
|
||||
// drive to work
|
||||
c.Stop();
|
||||
// get out of car
|
||||
}
|
||||
|
||||
func main() {
|
||||
m := Mercedes{Car{4, nil}}
|
||||
fmt.Println("A Mercedes has this many wheels: ", m.numberOfWheels())
|
||||
m.GoToWorkIn()
|
||||
m.sayHiToMerkel()
|
||||
}
|
||||
/* Output:
|
||||
A Mercedes has this many wheels: 4
|
||||
Car is started
|
||||
Car is stopped
|
||||
Hi Angela!
|
||||
*/
|
Reference in New Issue
Block a user