golang继承的简单应用

package main

import (
	"fmt"
)

//继承可以解决代码复用,让编程更加接近人类思维
//当多个结构体存在相同属性和方法时,可以从这些结构体中抽象出结构体,在该结构体中定义这些相同的属性和方法
//其他结构体不需要重新定义这些属性和方法,只需要嵌套一个匿名结构体即可
//也就是说golang中,如果一个struct嵌套了另一个匿名结构体,那么这个结构体可以直接访问匿名结构体的字段和方法,从而实现了继承的特性

type Student struct {
	Name  string
	Age   int
	Score int
}
type Pupil struct {
	Student//嵌入匿名结构体Student
}
type Graduate struct {
	Student
}

func (stu *Student) ShowInfo() {

	fmt.Printf("学生名=%v 年龄=%v 成绩=%v\n", stu.Name, stu.Age, stu.Score)
}
func (stu *Student) SetScore(score int) {
	stu.Score = score
}
func (stu *Pupil) testing() {
	fmt.Println("小学生正在考试中....")
}
func (stu *Graduate) testing() {
	fmt.Println("大学生正在考试中....")
}
func main() {

	pupil := &Pupil{}
	pupil.Student.Name = "tom"
	pupil.Student.Age = 8
	pupil.testing()
	pupil.Student.SetScore(80)
	pupil.Student.ShowInfo()

	graduate := &Graduate{}
	graduate.Student.Name = "jack"
	graduate.Student.Age = 22
	graduate.testing()
	graduate.Student.SetScore(90)
	graduate.Student.ShowInfo()
}

  

posted @ 2022-03-10 10:20  Star_Gazer  阅读(277)  评论(0编辑  收藏  举报