1.对象的创建
package main
import "fmt"
// 声明一种新的数据类型 ...
// type myInt int
// 定义一个结构体
type Hero struct {
Name string
Ad int
Level int
}
// 给类增加一个方法
func (this *Hero) GetName() {
fmt.Println("name =", this.Name)
}
// 给类增加一个方法
func (this *Hero) SetName() {
this.Name = "我改名了"
}
func main() {
// 创一个对象
hero := Hero{
Name: "xiang",
Ad: 1,
Level: 99,
}
hero.SetName()
hero.GetName()
}
2.继承
struct中继承即可
3.多态(interface实现)
package main
import "fmt"
// 定义一个接口,本质是一个指针
type AnimalIF interface {
Sleep()
GetColor() string // 带返回值
GetType() string
}
// 具体的类
type Cat struct {
color string
}
func (this *Cat) Sleep() {
fmt.Println("cat sleep")
}
func (this *Cat) GetColor() string {
return this.color
}
func (this *Cat) GetType() string {
return "cat"
}
type Dog struct {
color string
}
func (this *Dog) Sleep() {
fmt.Println("dog sleep")
}
func (this *Dog) GetColor() string {
return this.color
}
func (this *Dog) GetType() string {
return "dog"
}
func ShowAnimal(animal AnimalIF) {
animal.Sleep()
fmt.Println("animal color is", animal.GetColor())
fmt.Println("animal type is", animal.GetType())
}
// 不需要继承,直接重写方法即可, 一个接口定义了2个类, 即AnimalIF为父类
func main() {
/*
// 创一个指针
var animal AnimalIF //接口的数据类型,父类的指针
animal = &Cat{"green"}
animal.GetColor()
animal.GetType()
animal.Sleep() // animal调用cat的sleep() 实现多态
animal = &Dog{"大黄"}
animal.GetColor()
animal.GetType()
animal.Sleep() // animla调用dog的sleep()方法,实现多态
*/
cat := Cat{"大黄狗"}
dog := Dog{"小黑猫"}
ShowAnimal(&cat)
ShowAnimal(&dog)
}
-
有一个父类(interface实现)
-
有子类(实现了父类的全部接口方法)
-
父类类型的变量(指针)指向了子类的具体数据变量
感觉兴趣的小伙伴可以加好友一起交流!!