inheritance_car.go 864 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // inheritance_car.go
  2. package main
  3. import (
  4. "fmt"
  5. )
  6. type Engine interface {
  7. Start()
  8. Stop()
  9. }
  10. type Car struct {
  11. wheelCount int
  12. Engine
  13. }
  14. // define a behavior for Car
  15. func (car Car) numberOfWheels() int {
  16. return car.wheelCount
  17. }
  18. type Mercedes struct {
  19. Car //anonymous field Car
  20. }
  21. // a behavior only available for the Mercedes
  22. func (m *Mercedes) sayHiToMerkel() {
  23. fmt.Println("Hi Angela!")
  24. }
  25. func (c *Car) Start() {
  26. fmt.Println("Car is started")
  27. }
  28. func (c *Car) Stop() {
  29. fmt.Println("Car is stopped")
  30. }
  31. func (c *Car) GoToWorkIn() {
  32. // get in car
  33. c.Start()
  34. // drive to work
  35. c.Stop()
  36. // get out of car
  37. }
  38. func main() {
  39. m := Mercedes{Car{4, nil}}
  40. fmt.Println("A Mercedes has this many wheels: ", m.numberOfWheels())
  41. m.GoToWorkIn()
  42. m.sayHiToMerkel()
  43. }
  44. /* Output:
  45. A Mercedes has this many wheels: 4
  46. Car is started
  47. Car is stopped
  48. Hi Angela!
  49. */