golang面向对象总结

来源:互联网 发布:甲骨文数据库怎么使用 编辑:程序博客网 时间:2024/05/29 11:50
[plain] view plaincopy
  1. type $name struct{  
  2.   property01 int  
  3.   property02 int  
  4.   }  

Golang里面的方法和接口都是基于这里type *** struct创建的类型,这里其实可以理解为:

[php] view plaincopy
  1. class $name {  
  2.   public int property01;  
  3.   public int property02;  
  4.   }  

类型就是类。

所以我们说是类型的某个方法,类型实现了某个接口。


    类型是属性的集合,接口是方法的集合   

函数的定义:func       $funcName ( ) ( ){}

方法的定义:func  ( )  $funcName ( ) ( ){}

Func (成员变量 类型) funname(局部变量 类型,局部变量 类型) (返回值类型) {}

成员变量是通过type来定义的。

函数的参数列表是需要传递的局部变量。

golang的方法的类型签名:
1.指明要给哪个类型添加方法;
2.指定调用此方法的变量的是值类型还是指针类型,调用此方法的变量必须按照类型签名这里来决定是用值类型还是指针类型,golang能自动转换,但你必须确保这个变量能被正确转换为相应的值或指针。例如,一个接口类型的变量就没法被转换为一个struct的指针。


继承:

当一个类型B的某个字段(匿名字段)的类型是另一个类型 A的时候,那么类型 A所拥有的全部字段都被隐式地引入了当前定义的这个类型B。这样就实现了继承。B类型的变量就可以调用A的所有属性和方法。也就是说A继承了B

定义继承时,子类中一般都含有一个类型是父类的匿名字段匿名字段就是用来实现继承的

[plain] view plaincopy
  1. package main  
  2. import (  
  3.     "fmt"  
  4. )  
  5. type Animal struct {  
  6.     Name string  
  7.     Age  int  
  8. }  
  9. func (ani *Animal) GetAge() int {  
  10.     return ani.Age  
  11. }  
  12. type Dog struct {  
  13.     Animal //Animal匿名字段  
  14. }  
  15. func main() {  
  16.     dog := Dog{Animal{"dog", 10}}  
  17.     fmt.Println(dog.Age)  
  18.     fmt.Println(dog.GetAge())  
  19. }  

方法的重写

如果一个类型B实现了作为其属性的类型A中的方法。那么这个类型B值调用方法的时候调用的是自己类型B的方法,而不是属性类型A的方法。
代码如下:

[plain] view plaincopy
  1. package main  
  2. import (  
  3.     "fmt"  
  4. )  
  5. type Animal struct {  
  6.     Name string  
  7.     Age  int  
  8. }  
  9. func (ani *Animal) GetAge() int {  
  10.     return ani.Age  
  11. }  
  12. type Dog struct {  
  13.     Animal //Animal匿名字段  
  14. }  
  15. func (ani Dog) GetAge() int {  
  16.     return ani.Age + 1  
  17. }  
  18. func main() {  
  19.     dog := Dog{Animal{"dog", 10}}  
  20.     fmt.Println(dog.Age)  
  21.     fmt.Println(dog.GetAge())  
  22. }  

接口

接口

1)定义接口类型
定义接口,接口中可以有未实现的方法。

[plain] view plaincopy
  1. type Animal interface {  
  2.     GetAge() int  
  3. }  

1)实现接口类型
如果某个类型实现了接口的所有方法。则这个类型实现了这个接口。

[plain] view plaincopy
  1. type Animal interface {  
  2. GetAge() int  
  3. }  
  4. type Dog struct {  
  5. Name string  
  6. Age  int  
  7. }  


//实现GetAge()方法则实现了Animal接口 

[plain] view plaincopy
  1. func (ani Dog) GetAge() int {  
  2. return ani.Age  
  3. }  
0 0
原创粉丝点击