java 封装 继承 多态,【Golang】封装,继承与多态

本文详细探讨了Go语言中如何实现面向对象的三大特性——封装、继承和多态。封装通过首字母大小写的约定来控制访问权限,类似于Java中的public和private。尽管Go不直接支持继承,但可以通过结构体组合实现类似效果。多态则通过实现接口来达成,只要struct实现了interface的所有方法,就认为实现了该接口。文中通过实例展示了这些概念在Go语言中的应用。
摘要由CSDN通过智能技术生成

面向对象的基本思想主要体现在封装,继承以及多态等的设计与运用上。

这篇文章主要讲述,封装、继承与多态在golang中是如何实现的。

封装

封装主要是通过访问权限控制实现的。

在Java中,共有public 、protected、default、private这四种权限控制。

而相应的在golang中,是通过约定来实现权限控制的。变量名首字母大写,相当于java中的public,首字母小写,相当于private。同一个包中访问,相当于default。由于go没有继承,也就没有protected。

继承

虽然golang的语法没有继承,但是可以通过相应的结构体之间的组合来实现类似的继承效果。

例子如下:

package main

import "fmt"

type inner struct {

i string

}

func (in *inner) innerMethod() {

fmt.Println("inner's innerMethod!!!")

}

type outter struct {

s1 string

s2 int

s3 bool

inner

}

func main() {

o := new(outter)

fmt.Printf("o.i %v\n", o.i)

o.i = "inner"

fmt.Printf("o.i %v\n", o.i)

o.innerMethod()

}

输出结果

o.i

o.i inner

inner's innerMethod!!!

也可以重写innerMethod方法,例子如下:

package main

import "fmt"

type inner struct {

i string

}

func (in *inner) innerMethod() {

fmt.Println("inner's innerMethod!!!")

}

type outter struct {

s1 string

s2 int

s3 bool

inner

}

func (o *outter) innerMethod(s string) {

fmt.Println("outter's innerMethod!!!")

}

func main() {

o := new(outter)

fmt.Printf("o.i %v\n", o.i)

o.i = "inner"

fmt.Printf("o.i %v\n", o.i)

//o.innerMethod()

o.innerMethod("test")

}

输出结果:

o.i

o.i inner

outter's innerMethod!!!

多态

Java 中的多态是通过 extends class 或者 implements interface 实现的,在 golang 中既没有 extends,也没有 implements ,那么 go 中多态是如何实现的呢 ?

答案:在golang中,只要某个struct实现了某个interface中的所有方法,那么我们就认为,这个struct实现了这个类。

例子如下:

package main

import "fmt"

type Person interface {

Action()

}

type Girl struct {

Name string

}

func (g *Girl) Action() {

fmt.Printf("My name is %v\n", g.Name)

}

type Boy struct {

Name string

}

func (b *Boy) Action() {

fmt.Printf("My name is %v\n", b.Name)

}

func main() {

girl := &Girl{Name: "Beautiful"}

boy := &Boy{Name: "Handsome"}

girl.Action()

boy.Action()

}

输出结果:

My name is Beautiful

My name is Handsome

有疑问加站长微信联系(非本文作者)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值