首页 > 其他 > 详细

面向对象编程三大特征5

时间:2019-08-26 23:14:41      阅读:94      评论:0      收藏:0      [点我收藏+]

Go接口注意事项和细节说明:

注意事项和细节:

1)接口本身不能创建实例,但是可以指向一个实现了该接口的自定义类型的变量(实例)

type AInterface interface {
  Say()
}

type Stu struct {
  Name string
}

func (stu Stu) Say() {
  fmt.Println("Stu Say()")
}

func main() {
  var stu Stu
  var a AInterface = stu
  a.Say()
}

2)接口中所有的方法都没有方法体,即都是没有实现的方法。

3)在Golang中,一个自定义类型需要将某个接口的所有方法都实现,我们说这个自定义类型实现了该接口。

4)一个自定义类型只有实现了某个接口,才能将该自定义类型的实例(变量)赋给接口类型。

5)只要是自定义数据类型,就可以实现接口,不仅仅是结构体类型。

type AInterface interface {
  Say()
}

type integer int

func (i integer) Say() {
  fmt.Println("integer Say i =", i)
}

func main() {
  var i integer = 10
  var b AInterface = i
  b.Say()
}

6)一个自定义类型可以实现多个接口

type AInterface interface {
  Say()
}

type BInterface interface {
  Hello()
}

type Monster struct {

}

func (m Monster) Hello() {
  fmt.Println("Monster Hello()")
}

func (m Monster) Say() {
  fmt.Println("Monster Say()")
}

func main() {
  var monster Monster
  var c AInterface = monster
  var d BInterface = monster
  c.Say()    //不可以c.Hello(),因为AInterface里是没有Hello()这个方法。
  d.Hello()   //同理,不可以d.Say()
}

7)Golang接口中不能有任何变量

type AInterface interface {
  Name string //这样是不可以的,会报语法错误。
  Say()
}

8)一个接口(比如A接口) 可以继承多个别的接口(比如B,C接口),这时如果要实现A接口,也必须将B,C接口的方法也全部实现。

type BInterface interface {
  test01()
}

type CInterface interface {
  test02()
}

type AInterface interface {
  BInterface
  CInterface
  test03()
}

//如果需要实现AInterface,就需要将BInterface CInterface的方法都实现
type Stu struct {

}

func (stu Stu) test01() {

}

func (stu Stu) test02() {

}

func (stu Stu) test03() {

}

func main() {
  var stu Stu
  var a AInterface = stu
  a.test01()
}


9)interface类型默认是一个指针(引用类型),如果没有对interface初始化就使用,那么会输出nil

10)空接口interface{} 没有任何方法,所以所有类型都实现了空接口,即我们可以把任何一个变量赋给空接口。

type BInterface interface {
  test01()
}

type CInterface interface {
  test02()
}

type AInterface interface {
  BInterface
  CInterface
  test03()
}

//如果需要实现AInterface,就需要将BInterface CInterface的方法都实现
type Stu struct {

}

func (stu Stu) test01() {

}

func (stu Stu) test02() {

}

func (stu Stu) test03() {

}

type T interface {

}


func main() {
  var stu Stu
  var a AInterface = stu
  a.test01()

  var t T = stu //ok
  fmt.Println(t)

  var t2 interface{} = stu
  var num1 float64 = 8.8
  t2 = num1
  t = num1
  fmt.Println(t2, t)
}

面向对象编程三大特征5

原文:https://www.cnblogs.com/green-frog-2019/p/11415441.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!