Go面向对象编程OOP的实现

  • 在go 中 在函数名前加上一个声明(Type *Type)表明该方法是属于哪个对象(Type),以此来实现OOP,且特别注意,在go中因为没有继承的概念,所以只能使用组合这种方式来实现代码复用
  • func (Type *Type) func_Name(args) (return list){}
package demo
/*
@Author:David Ma
@Content:go中的面向对象编程(oop)的实现,以及类型别名和组合在使用时的区别
@Date:202-12-01 15:41
*/
import (
	"fmt"
)

type Person struct {
	Name string
}

// 类型别名
type Student2 Person

//类型组合
type Student1 struct {
	Person
	SID int
}

// go中oop的实现,在函数名前加上一个声明(Type *Type)表明该方法是属于哪个对象(Type)
func (p *Person) WakeUp(){
	fmt.Printf("%s waking up\n", p.Name)
}

func (p *Person) Eat(){
	fmt.Printf("%s eating\n", p.Name)
}

func (p *Person) Sleep(){
	fmt.Printf("%s sleeping\n", p.Name)
}

func (s *Student1) Study(){
	fmt.Printf("%s learning\n", s.Name)
}

func (s *Student2) Study(){
	fmt.Printf("%s learning\n", s.Name)
}

func (s *Student1) Student1Daily() {
	s.WakeUp()
	s.Eat()
	s.Study()
	s.Sleep()
}

//虽然说类型别名没有创建新类型,只是换了个名字起了个小名,但是在OOP中,无法利用类型别名来实现代码复用,只能利用组合来实现代码复用
//func (s *Student2) Student2Daily() {
//	s.WakeUp() // compile error:Unresolved reference 'WakeUp'
//	s.Eat()  // compile error:Unresolved reference 'WakeUp'
//	s.Study()
//	s.Sleep() // compile error:Unresolved reference 'WakeUp'
//}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值