Go语言面向对象笔记

文章目录

继承

  1. 通过匿名字段来实现继承,使用结构体嵌套结构体
type person struct {
	name string
	age int
	sex string
}
//结构体嵌套结构体
type Student struct {
	//通过匿名字段实现继承操作
	person //结构体名称作为结构体成员
	id int
	score int
}

func main() {
	var stu Student
	stu.id=1
	stu.score=100
	stu.name="王哈"
	stu.age=18
	stu.sex="女"
	//stu.person.sex="男"
	fmt.Print(stu)
}
  1. 指针匿名继承

和上面的区别就在于,如果按照上面的写法,我们不写new 的一步操作,就会造成空指针异常,因为我们使用的person是一个空地址。所以需要将其实现new出来才能对属性字段操作。

type person1 struct {
	name string
	age int
	sex string
}
type student1 struct {
	*person1 //指针匿名字段
	id int
	score int
}
func main() {
	var stu student1
	stu.person1 = new(person1)
	stu.name="王哈"
	fmt.Print(stu.name)//王哈
}

  1. 多重继承
type TestA struct {
	age int 
}
type TestB struct {
	TestA
}
type TestC struct {
	TestB
}
func main() {
	var c TestC
	c.TestB.TestA.age=15
}
  1. 接口的继承
type interA interface {//子集

}
type interB interface {//超集
	interA
}

多态

和其他的oop的概念相同

  1. 使用接口实现多态
package main

import "fmt"

type personD struct {
	name string
	sex string
	age int
}

type studentD struct {
	personD
	score int
}
type teacherD struct {
	personD
	subject string
}

func (s *studentD) say(){
	fmt.Println("student")
}
func (t *teacherD) say(){
	fmt.Println("teacher")
}
type personer interface {
	say()
}
// 多态实现
//说白了就是通过接口,作为函数参数,去实现接口的统一处理
func sayHello(p personer)  {
	p.say()
}
func main() {
	var p personer
	p=&studentD{}
	sayHello(p)//student
	p=&teacherD{}
	sayHello(p)//teacher
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值