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
}
发布了296 篇原创文章 · 获赞 53 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_41936805/article/details/104095964