原文: http://golangtutorials.blogspot.com/2011/06/inheritance-and-subclassing-in-go-or.html

---------------------------------------------------------------------------------------------

Those of you used to other object oriented languages probably already know what inheritance and subclassing is. In simple terms, it is the ability of one type to inherit the behavior of another type. An Employee has all the behaviors of a Human, and then some more. A Ferrari has all the behaviors of a Car, and some more. An Aston Martin has all the behaviors of a Car, and then some more, but not the same as that of a Ferrari. So if we could generalize a Car and define behaviors for it, then both a Ferrari and an Aston Martin could reuse it, instead of each redoing it from scratch. Basically, it inherits the behavior of a more generalized type or class. Or in the language of object oriented programming, there could be a class and a subclass of it, where the subclass appears to inherit all the behaviors of the parent class. The subclass could go on to define more specialized behaviors for itself.

Now what does this mean for us in programming? Assume you had the class Car and it has a member method called numberOfWheels(). If we create a subclass Ferrari of Car, what it means in coding is that we should automatically have a Ferrari.numberOfWheels() - i.e. the subclass gets the super class’ behaviors or its methods.

With what we’ve learnt already with Anonymous fields in structs and Methods on structs, we can achieve the same paradigm in Go. If, like me, you have been more used to object oriented programming so far, a couple of examples will help explain how.

Full code

package main

import "fmt"

type Car struct {
wheelCount int
}
// define a behavior for Car
func (car Car) numberOfWheels() int {
return car.wheelCount
} type Ferrari struct {
Car //anonymous field Car
}
func main() {
f := Ferrari{Car{4}}
fmt.Println("A Ferrari has this many wheels: ", f.numberOfWheels()) //no method defined for Ferrari, but we have the same behavior as Car.
}
A Ferrari has this many wheels: 4

In the above program, we have only defined a method or behavior for Car. Since we then defined Car as an anonymous field in Ferrari, the latter class automatically can call on all the visible behaviors/methods of the anonymous field type. So here, we have not subclassed a parent class, but composed it. But the effect is the very same - you have all the behaviors of the parent with none of the frills of object oriented programming. C’mon, you have to agree with me that that is cool! Let’s bring in the Aston Martin also now, and this time add some individual behavior in addition to that inherited.

Full code

package main

import "fmt"

type Car struct {
wheelCount int
} func (car Car) numberOfWheels() int {
return car.wheelCount
} type Ferrari struct {
Car
} // a behavior only available for the Ferrari
func (f Ferrari) sayHiToSchumacher() {
fmt.Println("Hi Schumacher!")
} type AstonMartin struct {
Car
} // a behavior only available for the AstonMartin
func (a AstonMartin) sayHiToBond() {
fmt.Println("Hi Bond, James Bond!")
} func main() {
f := Ferrari{Car{4}}
fmt.Println("A Ferrari has this many wheels: ", f.numberOfWheels()) //has car behavior
f.sayHiToSchumacher() //has Ferrari behavior a := AstonMartin{Car{4}}
fmt.Println("An Aston Martin has this many wheels: ", a.numberOfWheels()) //has car behavior
a.sayHiToBond() //has AstonMartin behavior
}
A Ferrari has this many wheels: 4
Hi Schumacher!
An Aston Martin has this many wheels: 4
Hi Bond, James Bond!

In the above program, both the Aston Martin and the Ferrari, behave like a car - since both can access the numOfWheels method from Car as if it was directly available in it. In addition, it defines its own behaviors that only itself can use. So the neither the Car nor the AstonMartin can call sayHiToSchumacher; similarly only the AstonMartin can call sayHiToBond and neither Ferrari nor Car can do that.

In short, by using Go’s concept of anonymous fields, we arrive at the same concept as subclassing and inheritance. It would appear inside out at first that to subtype something, you put the parent type within the sub type.

Inheritance and subclassing in Go - or its near likeness的更多相关文章

  1. Less is exponentially more

    Less is exponentially more  (原文出处:rob pike 博客,https://commandcenter.blogspot.jp/2012/06/less-is-expo ...

  2.  Go is more about software engineering than programming language research.

    https://talks.golang.org/2012/splash.article Go at Google: Language Design in the Service of Softwar ...

  3. Effective Java 17 Design and document for inheritance or else prohibit it

    Principles The class must document its self-use of overridable methods. A class may have to provide ...

  4. 代码的坏味道(12)——平行继承体系(Parallel Inheritance Hierarchies)

    坏味道--平行继承体系(Parallel Inheritance Hierarchies) 平行继承体系(Parallel Inheritance Hierarchies) 其实是 霰弹式修改(Sho ...

  5. 5.Inheritance Strategy(继承策略)【EFcode-first系列】

    我们已经在code-first 约定一文中,已经知道了Code-First为每一个具体的类,创建数据表. 但是你可以自己利用继承设计领域类,面向对象的技术包含“has a”和“is a”的关系即,有什 ...

  6. single-table inheritance 单表继承

    type 字段在 Rails 中默认使用来做 STI(single-table inheritance),当 type 作为普通字段来使用时,可以把SIT的列设置成别的列名(比如不存在的某个列). 文 ...

  7. C++: virtual inheritance and Cross Delegation

    Link1: Give an example Note: I think the Storable::Write method should also be pure virtual. http:// ...

  8. React之Composition Vs inheritance 组合Vs继承

    React的组合   composition: props有个特殊属性,children,组件可以通过props.children拿到所有包含在内的子元素, 当组件内有子元素时,组件属性上的child ...

  9. What is the difference between the ways to implement inheritance in javascript.

    see also : http://www.w3school.com.cn/js/pro_js_inheritance_implementing.asp http://davidshariff.com ...

随机推荐

  1. 基于TreeSoft实现异构数据同步

    一.为了解决数据同步汇聚,数据分发,数据转换,数据维护等需求,TreeSoft将复杂的网状的同步链路变成了星型数据链路.     TreeSoft作为中间传输载体负责连接各种数据源,为各种异构数据库之 ...

  2. 管道式编程(Pipeline Style programming)

    受 F# 中的管道运算符和 C# 中的 LINQ 语法,管道式编程为 C# 提供了更加灵活性的功能性编程.通过使用 扩展函数 可以将多个功能连接起来构建成一个管道. 前言 在 C# 编程中,管道式编程 ...

  3. Center Message

    企鹅号 头条号 大鱼号 百家号 趣头条

  4. 在ensp上配置通过Stelnet登录系统

    我们为什么我们要采用Stelent登录? 因为不安全,我们要采用更加安全的方式,双向加密,通过ssh网络安全协议 下面我们开始实验:使用路由器R1模拟PC,作为SSH的客户端:路由器R2作为SSH的服 ...

  5. socket编程方法,概念

    "蚓无爪牙之利,筋骨之强,上食埃土,下饮黄泉,用心一也.蟹六跪而二螯,非蛇鳝之穴无可寄托者,用心躁也." ------------------------------------- ...

  6. 【转帖】2019年中国5G行业细分市场发展现状和市场前景分析 通信基站数量快速增长

    2019年中国5G行业细分市场发展现状和市场前景分析 通信基站数量快速增长 中国有 600多万个基站 平均每200个人 一个基站.. 一个基站十万块钱的话 相当于 每个人 需要分摊 500块钱. ht ...

  7. BJFU-208-基于顺序存储结构的图书信息表的最贵图书的查找

    #include<stdio.h> #include<stdlib.h> #define MAX 1000 typedef struct{ double no; char na ...

  8. python第三天---列表的魔法

    # list 列表 # 中括号括起来,逗号分隔每个元素, # 列表中可以是数字字符串.列表等都可以放进去 list1 = [123, "book", "手动", ...

  9. PAT(B) 1059 C语言竞赛(C)

    题目链接:1059 C语言竞赛 (20 point(s)) 题目描述 C 语言竞赛是浙江大学计算机学院主持的一个欢乐的竞赛.既然竞赛主旨是为了好玩,颁奖规则也就制定得很滑稽: 冠军将赢得一份" ...

  10. PAT(B) 1064 朋友数(Java)

    题目链接:1064 朋友数 (20 point(s)) 题目描述 如果两个整数各位数字的和是一样的,则被称为是"朋友数",而那个公共的和就是它们的"朋友证号". ...