寮步网站建设极致发烧,网页设计费,宝安做网站公司乐云seo,中国制造网官方网站国际站Golang中面向对象类的表示与封装 package mainimport fmt// 如果类名首字母大写#xff0c;表示其他包也能够访问
type Hero struct {// 如果类的属性首字母大写#xff0c;表示该属性是对外能够访问的#xff0c;否则的话只能够类的内部访问Name stringAd …Golang中面向对象类的表示与封装 package mainimport fmt// 如果类名首字母大写表示其他包也能够访问
type Hero struct {// 如果类的属性首字母大写表示该属性是对外能够访问的否则的话只能够类的内部访问Name stringAd intLevel int
}
/*
func (this Hero) GetName() {fmt.Println(Name , this.Name)
}func (this Hero) SetName(newName string) {// this 是调用该方法的对象的一个副本拷贝this.Name newName
}func (this Hero) Show() {fmt.Println(Name , this.Name)fmt.Println(Ad , this.Ad)fmt.Println(Level , this.Level)
}*/func (this *Hero) GetName() {fmt.Println(Name , this.Name)
}func (this *Hero) SetName(newName string) {// 此时this就不是副本而是一个指针this.Name newName
}func (this *Hero) Show() {fmt.Println(Name , this.Name)fmt.Println(Ad , this.Ad)fmt.Println(Level , this.Level)
}func main() {hero : Hero{Name: 大将军,Ad: 111,Level: 10,}hero.Show()fmt.Println()hero.SetName(小将军)hero.Show()}
Golang中面相对象继承 package mainimport fmt// 定义父类
type Human struct {name stringsex string
}func (this *Human) Eat() {fmt.Println(Human.Eat()...)
}func (this *Human) Walk() {fmt.Println(Human.Walk()...)
}
// type SuperMan struct {Human // SuerMan类型继承Human类方法level int
}// 重定义父类的方法Eat()
func (this *SuperMan) Eat() {fmt.Println(SuperMan.Eat()...)
}func (this *SuperMan) Fly() {fmt.Println(SuperMan.Fly()...)
}func (this *SuperMan) PrintMan() {fmt.Println(name , this.name)fmt.Println(sex , this.sex)fmt.Println(level , this.level)
}func main() {h : Human{张三, 男}h.Eat()h.Walk()fmt.Println()//s : SuperMan{Human{李四,女,},11,}var s SuperMans.name 李四s.sex 女s.level 11s.Walk() // 父类的方法s.Eat() // 子类的方法s.Fly() // 子类的方法fmt.Println()s.PrintMan()}Golang中面向对象多态的实现与基本要素 package mainimport fmt// 本质是一个指针
type AnimalIF interface {Sleep() // 让动物睡觉GetColor() string // 获取动物的颜色GetType() string // 获取动物的类型
}//
// 具体的类
type Cat struct {color string
}
func (this *Cat) Sleep() {fmt.Println(Cat is 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 is Sleep)
}
func (this *Dog) GetColor() string {return this.color
}
func (this *Dog) GetType() string {return Dog
}// func showAnimal(animal AnimalIF) {animal.Sleep()fmt.Println(color , animal.GetColor())fmt.Println(type , animal.GetType())
}func main() {//var animal AnimalIF // 接口的数据类型父类指针////animal Cat{Green}//animal.Sleep() // 调用的就是Cat的Sleep()方法////animal Dog{Yellow}//animal.Sleep() // 调用的就是Dog的Sleep()方法cat : Cat{Green}showAnimal(cat)fmt.Println(-----)dog : Dog{Yellow}showAnimal(dog)fmt.Println(-----)
}