Golang中面向对象类的表示与封装
package main import "fmt"
type Hero struct { Name stringAd int Level int
}
func ( this * Hero ) GetName ( ) { fmt. Println( "Name = " , this. Name)
} func ( this * Hero ) SetName ( newName string) { 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 main import "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 level int
}
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( "=====================" ) var s SuperMan s. name = "李四" s. sex = "女" s. level = 11 s. Walk( ) s. Eat( ) s. Fly( ) fmt. Println( "=====================" ) s. PrintMan( ) }
Golang中面向对象多态的实现与基本要素
package main import "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 ( ) { cat : = Cat { "Green" } showAnimal ( & cat) fmt. Println( "-----" ) dog : = Dog { "Yellow" } showAnimal ( & dog) fmt. Println( "-----" )
}