GO语言面向对象02---继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
 
import (
    "fmt"
)
 
type Dog struct {
    Name string
    Age int
}
 
func (d *Dog)bite()  {
    fmt.Printf("%s要咬你了\n", d.Name)
}
 
type PoliceDog struct {
    //一行代码拥有父类的全部成员(属性+方法)
    Dog
 
    //扩展出新的属性
    Skill string
}
 
//扩展出新的方法
func (pd *PoliceDog)DoPoliceJob(){
    fmt.Printf("%s正在执行警务工作:%s\n",pd.Name,pd.Skill)
}
 
//重写父类方法(overwrite)
func (d *PoliceDog)bite()  {
    fmt.Printf("%s要把你大卸八块了\n", d.Name)
}
 
func main21() {
    pd := PoliceDog{}
    //通过子类对象访问父类成员
    pd.Name = "战狼"
    pd.bite()
 
    //访问子类独有成员
    pd.Skill = "徒手接RPG"
    pd.DoPoliceJob()
 
    //访问子类复写了的父类方法
    pd.bite()
}
 
func main() {
    //pd := PoliceDog{}
    //pd := PoliceDog{Dog{Name: "战狼"}, "徒手接炮弹"}
    //pd := PoliceDog{Dog: Dog{Name:"战狼"}}
    //pd := PoliceDog{Skill: "徒手接炮弹"}
    //pd := new(PoliceDog)
    pd := NewPoliceDog("战狼", 40, "徒手接炮弹")
    fmt.Println(pd.Name,pd.Age,pd.Skill)
    pd.bite()
    pd.DoPoliceJob()
}
 
func NewPoliceDog(name string,age int,skill string) *PoliceDog {
    //pd:=new(PoliceDog)
    //pd.Name=name
    //pd.Age=age
    //pd.Skill=skill
    pd := &PoliceDog{Dog{name, age}, skill}
    return pd
}

  

posted @   Ethan_Cheng  阅读(157)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示