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

本文深入探讨了Go语言如何通过struct、interface等特性实现面向对象编程的三大特性:封装、继承和多态。通过具体代码示例,展示了Go语言如何在没有传统面向对象概念的情况下,实现类似的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

学习面向对象之前,应该搞清楚,什么是面向对象?为什么用面向对象?以及使用面向对象有什么优缺点?不了解的同学可以找google 或baidu,此篇不再赘述。
go 没有对象(object)、类(class)等面向对象概念,但提供了struct,interface等特性实现类似的功能。面向对象有三大特性:封装、继承、多态,接下来我们看看go语言是怎么处理的。

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

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

继承

例子

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类型

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 接口类的子类。

以上为个人理解,如有不同意见或建议,欢迎回复,批评指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值