前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >go之面向对象 封装、继承、多态

go之面向对象 封装、继承、多态

原创
作者头像
IT工作者
发布2022-06-30 19:14:09
发布2022-06-30 19:14:09
48100
代码可运行
举报
文章被收录于专栏:程序技术知识程序技术知识
运行总次数:0
代码可运行

学习面向对象之前,应该搞清楚,什么是面向对象?为什么用面向对象?以及使用面向对象有什么优缺点?不了解的同学可以找google 或baidu,此篇不再赘述。

go 没有对象(object)、类(class)等面向对象概念,但提供了struct,interface等特性实现类似的功能。面向对象有三大特性:封装、继承、多态,接下来我们看看go语言是怎么处理的。

封装

struct是一种包含了命名域和方法的类型

例子

代码语言:javascript
代码运行次数:0
运行
复制
package main

import "fmt"

type Animal struct {
    Age  int32
    Type string
}

func (a *Animal) GetAge() int32 {
    return a.Age
}

func main() {
    a := Animal{Age: 18}
    fmt.Println(a.GetAge())
}

上面的例子定义了一个Animal 的struct类型, 该struct含有int32,和string类型的域;

同时Animal 上绑定了一个GetAge方法。

当然我们也可以从广义上将包(package)理解为一个封装。

方法、结构、变量、常量等,针对包的范围。

首字母大写代表 public

首字母小写代表 pirvate

继承

例子

代码语言:javascript
代码运行次数:0
运行
复制
package main

import "fmt"

type Animal struct {
    Age  int32
    Type string
}
type Dog struct {
    Animal
} 
func (a *Animal) GetAge() int32 {
    return a.Age
}

func main() {
    a := Dog{}
    a.Age=18
    fmt.Println(a.GetAge())
}

代码中Dog 的struct继承了Animal 所有的类型和方法

多态

这里我们需要借助interface类型

代码语言:javascript
代码运行次数:0
运行
复制
package main

import "fmt"

type Animal interface {
    GetAge() int32
    GetType() string
}

type Cat struct {
    Age  int32
    Type string
}
type Dog struct {
    Age  int32
    Type string
}

func (a *Dog) GetAge() int32 {
    return a.Age
}
func (a *Dog) GetType() string {
    return a.Type
}
func (c *Cat) GetAge() int32 {
    return c.Age
}
func (c *Cat) GetType() string {
    return c.Type
}
func Factory(name string) Animal {
    switch name {
    case "dog":
        return &Dog{Age: 20, Type: "DOG"}
    case "cat":
        return &Cat{Age: 20, Type: "CAT"}
    default:
        panic("No such animal")
    }
}

func main() {
    animal := Factory("dog")
    fmt.Println()
    fmt.Printf("%s max age is: %d", animal.GetType(), animal.GetAge())
    animal = Factory("cat")
    fmt.Printf("%s max age is: %d", animal.GetType(), animal.GetAge())
}

结果

DOG max age is: 20CAT max age is: 20

凡是实现了Animal 接口类所有的方法,如 Cat, Dog实现了Animal中的全部方法。它就被认为是Animal 接口类的子类。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档