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


    package main
    
    import (
    	"fmt"
    )
    
    type Dog struct {
    	Name string
    	Age int
    }
    
    func (d *Dog)bite()  {
    	fmt.Printf("%s要咬你了
    ", d.Name)
    }
    
    type PoliceDog struct {
    	//一行代码拥有父类的全部成员(属性+方法)
    	Dog
    
    	//扩展出新的属性
    	Skill string
    }
    
    //扩展出新的方法
    func (pd *PoliceDog)DoPoliceJob(){
    	fmt.Printf("%s正在执行警务工作:%s
    ",pd.Name,pd.Skill)
    }
    
    //重写父类方法(overwrite)
    func (d *PoliceDog)bite()  {
    	fmt.Printf("%s要把你大卸八块了
    ", 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
    }
    

      

  • 相关阅读:
    Hashmap实现原理
    策略模式
    Google Drive ubuntu
    numix Docky
    Google Drive 和 Dropbox 同步同一个文件夹目录
    sublime text 2
    matlab cell
    liteide
    taglist and nerdtree
    codeblocks
  • 原文地址:https://www.cnblogs.com/yunweiqiang/p/11893906.html
Copyright © 2020-2023  润新知