go语言(十一)----面向对象继承

一、面向对象继承

  1. 写一个父类
package main

import "fmt"

type Human struct {
	name string
	sex string
}

func (this *Human) Eat() {
	fmt.Println("Human.Eat()...")
}

func (this *Human) Walk() {
	fmt.Println("Human.Walk()...")
}

func main() {

	h := Human{"zhang3","femal"}
	h.Eat()
	h.Walk()

}

go语言(十一)----面向对象继承_第1张图片

  1. 子类继承 父类
type SuperMan struct {
	Human //superman类继承了human类的方法
	level int
}

  1. 子类的新方法
//重定义父类的方法Eat()
func (this *SuperMan) Eat() {
	fmt.Println("SuperMan.Eat()...")
}

//子类的新方法
func (this *SuperMan) Fly() {
	fmt.Println("Superman.Fly()...")
}
  1. 定义子类
    两种方法:
    第一种:
s :=SuperMan{Human{"li4","female"},88}

第二种:

var s SuperMan
	s.name = "lis4"
	s.sex = "female"
	s.level = 88
  1. 子类继承父类的使用
package main

import "fmt"

type Human struct {
	name string
	sex string
}

func (this *Human) Eat() {
	fmt.Println("Human.Eat()...")
}

func (this *Human) Walk() {
	fmt.Println("Human.Walk()...")
}
//重定义父类的方法Eat()
func (this *SuperMan) Eat() {
	fmt.Println("SuperMan.Eat()...")
}

//子类的新方法
func (this *SuperMan) Fly() {
	fmt.Println("Superman.Fly()...")
}


type SuperMan struct {
	Human //superman类继承了human类的方法
	level int
}

func (this *SuperMan) Print()  {

	fmt.Println("name = ",this.name)
	fmt.Println("sex = ",this.sex)
	fmt.Println("level = ",this.level)

}

func main() {

	h := Human{"zhang3","femal"}
	h.Eat()
	h.Walk()

	//定义一个子类对象
	//s :=SuperMan{Human{"li4","female"},88}
	var s SuperMan
	s.name = "lis4"
	s.sex = "female"
	s.level = 88

	s.Walk() //父类的方法
	s.Eat() //子类的方法
	s.Fly() //子类的方法

	//打印出来
	s.Print()

}

go语言(十一)----面向对象继承_第2张图片

你可能感兴趣的:(golang,开发语言,后端)