封装

  • Go没有 class,只有 struct 。struct里面就是成员变量,外面显示带有 this指针 的就是成员方法
  • Go没有什么访问限定符,若 类名/函数名首字母大写,本包/模块外可以访问调用,若首字母为小写,仅能本包内访问调用
  • 实现类方法时需要绑定指明为 this指针,否则 this 是调用该方法对象的一个副本(拷贝)
package main

import "fmt"

type Father struct {
	name string
	age  int
}

func (this *Father) Getname() string {
	fmt.Println("this name is ", this.name)
	return this.name
}

func (this *Father) Getage() int {
	fmt.Println("this age is ", this.age)
	return this.age
}

func (this Father) Setname1(name string) {
	// this 是调用该方法对象的一个副本(拷贝)
	this.name = name
}

func (this *Father) Setname2(name string) {
	// this 指针
	this.name = name
}

func main() {
	person := Father{"zhansan", 12}
	name := person.Getname()           
	fmt.Println("this name = ", name)  
	person.Setname1("xxx")
	person.Getname()                  
	person.Setname2("dasheng")
	person.Getname()                 
}
// 输出结果
this name is  zhansan
this name =  zhansan
this name is  zhansan
this name is  dasheng

继承

  • 直接在子类定义时注明父类即可继承,非常简洁方便
package main

import "fmt"

type Father struct {
	name string
	age  int
}

func (this *Father) Getname() string {
	fmt.Println("this name is ", this.name)
	return this.name
}

func (this *Father) Getage() int {
	fmt.Println("this age is ", this.age)
	return this.age
}

type Children struct {
	Father
	work string
}

func (this *Children) Getwork() string {
	fmt.Println("this work is ", this.work)
	return this.work
}

func main() {
	var c Children
	c.name = "zhansan"
	c.age = 22
	c.work = "IT"
	c.Getname()    
	c.Getage()     
	c.Getwork()    
}
//输出结果
this name is  zhansan
this age is  22
this work is  IT

多态

  • 类中必须实现接口中的 所有方法,才可以实现多态的效果
  • 调用时只需要向接口对象中传入调用对象的地址即可实现多态效果
  • 基本要素:
    • 父类(有接口)
    • 子类(实现了父类的全部接口方法)
    • 父类类型的变量(指针)指向子类的具体数据变量
package main

import "fmt"

type Animal interface {
	Sleep()
	GetColor()
}

type Cat struct {
	color string
}

func (this *Cat) Sleep() {
	fmt.Println("this Cat color is sleep")
}

func (this *Cat) GetColor() {
	fmt.Println("this Cat color is", this.color)
}

type Dog struct {
	color string
}

func (this *Dog) Sleep() {
	fmt.Println("this Dog color is sleep")
}

func (this *Dog) GetColor() {
	fmt.Println("this Cat color is", this.color)
}

func ShowSleep(animal Animal) {
	animal.Sleep()
}
func main() {
	var a Animal // 接口的数据类型, 父类指针
	a = &Cat{"yellow"}
	a.GetColor() // 调用的是Cat的GetColor(), 多态现象   OutPut:this Cat color is yellow

	a = &Dog{"black"}
	a.GetColor() // 调用的是Dog的GetColor(), 多态现象   OutPut:this Dog color is black

	cat := Cat{"green"}
	dog := Dog{"red"}
	ShowSleep(&cat) 
	ShowSleep(&dog) 
}
//输出结果
this Cat color is yellow
this Cat color is black
this Cat color is sleep
this Dog color is sleep