go语言基础 方法的继承

方法继承

子类和父类的关系。
子类对象可以直接访问父类的属性和方法
子类可以新增自己的属性和方法。

子类可以重写父类已有的方法。

package main

import (
   "fmt"
   "math"
)

//1.定义Animal的结构体
type Animal struct {
   name string
   age int
}
//2.定义Animal的方法
func (a Animal) eat()  {
   fmt.Println(a.name,",在吃东西。。。")
}
func (a Animal) printInfo()  { // Anmial的对象调用方法
   fmt.Printf("名字:%s,年龄:%d\n", a.name,a.age)
}

// 3.定义Cat和Dog继承
type Cat struct {
   Animal
   color string
}
// 因为eat(),在父类Animal已有,但是Cat重新实现了,所以叫重写:override
func (c Cat) eat(){
   fmt.Printf("小猫:%s,在吃鱼。。。\n",c.name)
}

type Dog2 struct {
   Animal
   sex string
}
// 子类新增的方法
func (d Dog2) lookDoor()  {
   fmt.Printf("%s,在看家。。\n",d.name)
}

func main()  {
   /*
   继承:结构体的嵌套
      子类可以直接访问父类的属性和方法
      子类可以新增自己的属性和方法
      子类可以重写父类的方法
    */
    a1 := Animal{"兔子",3}
    a1.eat()
    a1.printInfo()

    c1 := Cat{Animal{"Tom",3},"蓝灰色"}
    c1.eat()// 子类访问重写的方法。
    c1.printInfo()// 子类直接访问父类的方法

    d1:= Dog2{Animal{"啸天",2},"公狗"}
    d1.eat() //子类对象,访问父类的方法
    d1.printInfo() //

    d1.lookDoor()

    fmt.Println(math.Sqrt(8))//根号8,
    fmt.Println(math.Sqrt(9))
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值