封装
type Person struct {
Name string
age int
}
Name首字母大写,相当于Java中public修饰
age首字母小写,相当于Java中private修饰
继承
与其说继承,不如称为组合,通过组合的方式实现继承的效果
type Person struct{
Name string
}
type Teacher struct{
person Person
}
多态
go不支持编译时多态,比如java的重载。
但go可以通过接口实现运行时多态。
package main
import "fmt"
type Human interface {
Show()
}
type Chinese struct {
name string
age int
}
func (this *Chinese) Show() {
fmt.Println("我是", this.name, ",年龄", this.age)
}
type American struct {
name string
weight int
}
func (this *American) Show() {
fmt.Println("I am",this.name,",weight",this.weight)
}
func main() {
var human Human
chinese := Chinese{
name: "张三",
age: 100,
}
american := American{
name: "Bob",
weight: 100,
}
human = &chinese
human.Show()
human = &american
human.Show()
}
结果
我是张三,年龄100
I am Bob,weight 100