首页 > 编程语言 >【Go语言】面向对象编程(二):通过组合实现类的继承和方法重写

【Go语言】面向对象编程(二):通过组合实现类的继承和方法重写

时间:2024-06-11 16:32:41浏览次数:14  
标签:面向对象编程 animal fmt Dog dog Println Animal Go 重写

通过组合实现类的继承和方法重写

要实现面向对象的编程,就必须实现面向对象编程的三大特性:封装、继承和多态。

1 封装

类的定义及其内部数据的定义可以看作是类的属性,基于类定义的函数方法则是类的成员方法。

2 继承

Go 语言中,没有直接提供继承相关的语法实现,可以通过 组合 的方式间接实现类似的功能,所谓组合,就是将一个类型嵌入到另一个类型,从而构建新的类型结构。

具体实现如下所示:

  1. 定义一个基础的类 Animal,其中定义了 Name 属性以及 CallFavorFoodGetName 成员方法。

    type Animal struct {
    	Name string
    }
    
    func (a Animal) Call() string {
    	return "动物的叫声..."
    }
    func (a Animal) FavorFood() string {
    	return "爱吃的食物..."
    }
    func (a Animal) GetName() string {
    	return a.Name
    }
    
  2. 定义一个新的类 Dog,继承 Animal 类的属性和成员方法。

    type Dog struct {
    	Animal
    }
    
  3. main 方法中对 AnimalDog 进行调用测试。

    animal := GoClass.Animal{"中华田园犬"}
    dog := GoClass.Dog{animal}
    fmt.Println(dog.GetName())
    fmt.Println(dog.Call())
    fmt.Println(dog.FavorFood())
    

    在这里插入图片描述

3 多态

这里重写方法 FavorFoodCall,如下所示:

func (d Dog) FavorFood() string {
    return "骨头"
}
func (d Dog) Call() string {
    return "汪汪汪"
}

main 方法中进行调用,如下所示:

fmt.Print(dog.Animal.Call())
fmt.Println(dog.Call())
fmt.Print(dog.Animal.FavorFood())
fmt.Println(dog.FavorFood())

在这里插入图片描述

4 其他问题
4.1 多继承同名方法冲突处理

需要注意组合的不同类型之间包含同名方法,比如 AnimalPet 都包含了 GetName 方法,如果子类 Dog 没有重写该方法,直接在 Dog 实例上调用的话会报错:

func main() {
    animal := Animal{"中华田园犬"}
    pet := Pet{"宠物狗"}
    dog := Dog{animal, pet}
    fmt.Println(dog.GetName())
}

在这里插入图片描述

需要显式的指定调用那个父类的方法,修改如下则不报错:

func main() {
    animal := Animal{"中华田园犬"}
    pet := Pet{"宠物狗"}
    dog := Dog{animal, pet}
    fmt.Println(dog.GetName())
}

在这里插入图片描述

4.2 为组合类型设置别名

能够设置继承父类的名称,示例如下:

type Dog struct {
    Animal *GoClass.Animal
    Pet    *GoClass.Pet
}

animal := GoClass.Animal{"中华田园犬"}
pet := GoClass.Pet{"宠物狗"}
dog := Dog{&animal, &pet}
fmt.Println(dog.Pet.GetName())
fmt.Println(dog.Animal.GetName())

在这里插入图片描述

标签:面向对象编程,animal,fmt,Dog,dog,Println,Animal,Go,重写
From: https://blog.csdn.net/suu_an/article/details/139602351

相关文章

  • Go 语言中的闭包和递归【GO 基础】
    〇、什么是闭包和递归什么是闭包?闭包就是每次调用外层函数时,临时创建的函数作用域对象。因为内层函数作用域链中包含外层函数的作用域对象,且内层函数被引用,导致内层函数不会被释放,同时它又保持着对父级作用域的引用,这个时候就形成了闭包。所以闭包通常是在函数嵌套中形成的。/......
  • Dragon Boat Festival
    AstheDragonBoatFestivalapproaches,thevillagecamealivewiththebuzzofanticipation.Theairwasfilledwiththescentofstickyriceandthesweetaromaofbambooleaves,minglingwiththeearthyfragranceoftheriverbank.Thesunshonebrightl......
  • Zgo - maps
     packagemainimport("fmt""maps")funcdelete(kstring,vint)bool{returnv%2!=0}funcequal(v1int,v2float64)bool{returnfloat64(v1)==v2}funcmain(){m:=map[string]int{"one......
  • [1005] Convert a Shapely polygon to an Esri polygon using ArcPy
    ToconvertaShapelypolygontoanEsripolygonusingArcPy,youcanfollowthesesteps:CreateaShapelyPolygon:First,createyourdesiredShapelypolygonusingtheShapelylibraryinPython.ConverttoEsriPolygon:Usethearcpy.FromWKB()func......
  • Zgo - slices
     packagemainimport("fmt""slices")funcmain(){s1:=[]int{1,2,-1,-2}s2:=slices.Clone(s1)fmt.Printf("%p\n",s1)fmt.Printf("%p\n",s2)s1[2]=0s1[3]=0s1......
  • 《Optimizing the LINPACK Algorithm for Large-Scale PCIe-Based CPU-GPU Heterogene
    论文标题《OptimizingtheLINPACKAlgorithmforLarge-ScalePCIe-BasedCPU-GPUHeterogeneousSystems》为基于PCIe的大规模CPU-GPU异构系统优化LINPACK算法作者GuangmingTan、ChaoyangShui、YinshanWang、XianzhiYu和YujinYan来自中科院计算所初读摘要......
  • SSRF-gopher 协议扩展利用:突破网络限制的利器
    服务器端请求伪造(SSRF)是一种隐蔽且危险的安全漏洞,它允许攻击者欺骗服务器向其他服务器发送请求,从而访问或控制未经授权的系统。Gopher协议作为SSRF漏洞利用的利器,可以帮助攻击者突破网络限制,实现更高级的攻击目标。Gopher协议简介Gopher是一种在HTTP协议之前非常流......
  • Dragon Boat Festival
    TheDragonBoatFestival,withahistoryspanningoverathousandyears,isoneofthetraditionalChinesefestival.ItfallsonthefifthdayofthefifthmonthoftheChineselunarcalendar.Notonlydoesitembodythenoblecharacter,patriotism,andcon......
  • Django模版
    一、模板视图函数只是返回文本,而在实际生产环境中其实很少这样用,因为实际的页面大多是带有样式的HTML代码,这可以让浏览器渲染出非常漂亮的页面,目前市面上有非常多的模板系统,其中最知名最好用的是DTL和Jinja2。DTL是DjangoTemplateLanguage三个单词的缩写,也就是Django自带的模板......
  • Dragon Boat Festival
    TheDragonBoatFestivalisaspecialdayinChinathathappensonthefifthdayofthefifthmonthofthelunarcalendar.Asthefestivalapproaches,theairisfilledwiththescentofricedumplings,steaminginbambooleaves,asymbolofunityandrem......