zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【愚公系列】2022年08月 Go教学课程 030-对象继承

Go对象继承 2022 系列 课程 愚公 教学
2023-06-13 09:12:58 时间

文章目录


一、对象继承

1.对象继承的概念

继承是面向对象软件技术当中的一个概念,与多态、封装共为面向对象的三个基本特征。继承可以使得子类具有父类的属性和方法或者重新定义、追加属性和方法等。

但在go语言中并没继承的概念,只能通过组合来实现继承。组合就是通过对现有对象的拼装从而获得实现更为复杂的行为的方法。

  • 继承:一个struct嵌套了另外一个匿名的struct从而实现了继承。
  • 组合:一个struct嵌套了宁外一个struct的实例实现了组合。
type Animal  struct {

}

//继承
type Cat struct {
    //匿名
    *Animail
}

//组合
type Dog struct {
    animal Animal
}

2.对象继承的案例

2.1 普通类型

package main

import "fmt"

type Student struct {
	Person // 匿名字段,只有类型,没有成员的名字
	score  float64
}
type Teacher struct {
	Person
	salary float64
}
type Person struct {
	id   int
	name string
	age  int
}

func main() {
	//var stu Student=Student{Person{100,"愚公",31},90}
	// 部分初始化
	// var stu Student=Student{score:100}
	var stu Student = Student{Person: Person{id: 100}}
	fmt.Println(stu)
	//fmt.Println(stu1)
}

2.2 对象继承指针类型

package main

import "fmt"

type Student struct {
	*Person // 匿名字段
	score   float64
}
type Person struct {
	id   int
	name string
	age  int
}

func main() {
	var stu Student = Student{&Person{101, "愚公", 18}, 90}
	fmt.Println(stu.name)
}

3.对象继承成员值的修改

package main

import "fmt"

type Student struct {
	Person
	score float64
}
type Person struct {
	id   int
	name string
	age  int
}

func main() {

	var stu Student = Student{Person{101, "愚公1号", 18}, 90}
	var stu1 Student = Student{Person{102, "愚公2号", 18}, 80}
	stu.score = 100
	fmt.Println("愚公一号考试成绩:", stu.score)
	fmt.Println(stu1.score)
	fmt.Println(stu1.Person.id)
	fmt.Println(stu1.id)
}

4.对象的多重继承

package main

import "fmt"

type Student struct {
	Person
	score float64
}
type Person struct {
	Object
	name string
	age  int
}
type Object struct {
	id int
}

func main() {
	var stu Student
	stu.age = 18
	fmt.Println(stu.Person.age)
	stu.id = 101
	fmt.Println(stu.Person.Object.id)
}