golang面向对象总结
来源:互联网 发布:甲骨文数据库怎么使用 编辑:程序博客网 时间:2024/05/29 11:50
- type $name struct{
- property01 int
- property02 int
- }
Golang里面的方法和接口都是基于这里type *** struct创建的类型,这里其实可以理解为:
- class $name {
- public int property01;
- public int property02;
- }
类型就是类。
所以我们说是类型的某个方法,类型实现了某个接口。
类型是属性的集合,接口是方法的集合
函数的定义:func $funcName ( ) ( ){}
方法的定义:func ( ) $funcName ( ) ( ){}
Func (成员变量 类型) funname(局部变量 类型,局部变量 类型) (返回值类型) {}
成员变量是通过type来定义的。
函数的参数列表是需要传递的局部变量。
golang的方法的类型签名:
1.指明要给哪个类型添加方法;
2.指定调用此方法的变量的是值类型还是指针类型,调用此方法的变量必须按照类型签名这里来决定是用值类型还是指针类型,golang能自动转换,但你必须确保这个变量能被正确转换为相应的值或指针。例如,一个接口类型的变量就没法被转换为一个struct的指针。
继承:
当一个类型B的某个字段(匿名字段)的类型是另一个类型 A的时候,那么类型 A所拥有的全部字段都被隐式地引入了当前定义的这个类型B。这样就实现了继承。B类型的变量就可以调用A的所有属性和方法。也就是说A继承了B。
定义继承时,子类中一般都含有一个类型是父类的匿名字段。匿名字段就是用来实现继承的。
- package main
- import (
- "fmt"
- )
- type Animal struct {
- Name string
- Age int
- }
- func (ani *Animal) GetAge() int {
- return ani.Age
- }
- type Dog struct {
- Animal //Animal匿名字段
- }
- func main() {
- dog := Dog{Animal{"dog", 10}}
- fmt.Println(dog.Age)
- fmt.Println(dog.GetAge())
- }
方法的重写
如果一个类型B实现了作为其属性的类型A中的方法。那么这个类型B的值调用方法的时候调用的是自己类型B的方法,而不是属性类型A的方法。
代码如下:
- package main
- import (
- "fmt"
- )
- type Animal struct {
- Name string
- Age int
- }
- func (ani *Animal) GetAge() int {
- return ani.Age
- }
- type Dog struct {
- Animal //Animal匿名字段
- }
- func (ani Dog) GetAge() int {
- return ani.Age + 1
- }
- func main() {
- dog := Dog{Animal{"dog", 10}}
- fmt.Println(dog.Age)
- fmt.Println(dog.GetAge())
- }
接口
1 接口
1)定义接口类型
定义接口,接口中可以有未实现的方法。
- type Animal interface {
- GetAge() int
- }
1)实现接口类型
如果某个类型实现了接口的所有方法。则这个类型实现了这个接口。
- type Animal interface {
- GetAge() int
- }
- type Dog struct {
- Name string
- Age int
- }
//实现GetAge()方法则实现了Animal接口
- func (ani Dog) GetAge() int {
- return ani.Age
- }
0 0
- golang面向对象总结
- golang面向对象总结
- Golang初级系列教程-面向对象总结
- golang 面向对象
- golang面向对象
- golang struct 面向对象
- Golang的面向对象
- Golang(笔记) 面向对象
- Golang面向对象之类型、方法、多态
- golang学习笔记[2] 面向对象OOP
- golang中的面向对象的思想
- 面向对象设计思想与 golang 编程
- 面向对象程序设计总结
- 面向对象总结
- 面向对象常见问题总结
- 面向对象概念总结
- js面向对象总结
- C++面向对象总结
- 规划科寄回来
- 后台使用imagemagick的convert命令来处理图片真是太方便了。
- pig- Join 优化
- web.xml启动顺序
- 无纰漏实现无限转换
- golang面向对象总结
- QT读取xml文件,然后写入另外一个新的xml文件
- top bottom 百分比是相对于宽度
- python list中append()与extend()用法【转】http://blog.sina.com.cn/s/blog_76e94d210100vxr9.html
- AIX 进程控制
- Python机器学习库
- 栈和队列算法三之队列的基本操作
- 通过jQuery的attr修改onclick
- java和c++混合编程尝试