GO语言自学_005_类的嵌套_类的继承

代码
package main

import "fmt"

// 定义一个Human类

type Human struct {
  // 属性
  name   string
  age    int
  gender string
}

// 定义一个学生类嵌套Human类

type Student struct {
  hum    Human // 包含Human类型的变量,是嵌套
  school string
  score  float64
}

// 定义一个老师类,继承Human类

type Teacher struct {
  Human   //直接写Human类型,没有字段名,是继承
  subject string
}

// 外部绑定一个方法

func (h *Human) Eat() {
  fmt.Println("this is ", h.name, ", he/she eats.")
}

func main() {
  s1 := Student{
  // hum是个类的嵌套
  hum: Human{
    name:   "Lily",
    age:    12,
    gender: "female",
  },
  school: "Michigan University",
  score:  100,
}
fmt.Println("===== 类的嵌套使用 =====")
fmt.Println("s1:", s1.hum.name)
fmt.Println("s1:", s1.school)
fmt.Println("s1:", s1.score)
s1.hum.Eat()

t1 := Teacher{
  // 这里是继承来的
  Human: Human{
  age:    30,
  name:   "Wang",
  gender: "female",
  },
  subject: "Chinese",
}
fmt.Println("===== 类的继承使用 =====")
fmt.Println("t1:", t1.name)
fmt.Println("t1:", t1.subject)
fmt.Println("t1:", t1.gender)
// 这里继承的时候,虽没定义字段名称,但会自动创建一个默认同名字段。
// 目的是防止子类父类出现同名的状况。
fmt.Println("t1:", t1.Human.age)
t1.Eat()
}
结果
GOROOT=C:\Program Files\Go #gosetup
GOPATH=C:\gowork #gosetup
"C:\Program Files\Go\bin\go.exe" build -o C:\Users\ASUS\AppData\Local\Temp\GoLand\___go_build_03_struct_Inheritance_go.exe C:\gowork\src\03_struct_Inheritance.go #gosetup
C:\Users\ASUS\AppData\Local\Temp\GoLand\___go_build_03_struct_Inheritance_go.exe
===== 类的嵌套使用 =====
s1: Lily
s1: Michigan University
s1: 100
this is  Lily , he/she eats.
===== 类的继承使用 =====
t1: Wang
t1: Chinese
t1: female
t1: 30
this is  Wang , he/she eats.

Process finished with the exit code 0

posted @ 2022-09-05 08:08  顺心无忧  阅读(36)  评论(0编辑  收藏  举报