原文: 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. Flask 数据库连接

    Flask拥有丰富的扩展组件,数据库管理方面Flask-SQLAlchemy简化了数据库管理的操作.SQLAlchemy是一个很强大的关系型数据库框架,支持多种数据库后台.其不但提供了高层ORM,而且 ...

  2. 洛谷 题解 UVA247 【电话圈 Calling Circles】

    [题意] 如果两个人互相打电话(直接或者间接),则说他们在同一个电话圈里.例如,\(a\)打给\(b\),\(b\)打给\(c\),\(c\)打给\(d\),\(d\)打给\(a\),则这四个人在同一 ...

  3. js判断是Android还是iOS

    var u = navigator.userAgent, app = navigator.appVersion; var isAndroid = u.indexOf('Android') > - ...

  4. (四)Spring Boot官网文档学习

    文章目录 关于默认包的问题 加载启动类 配置 Bean管理和依赖注入 @SpringBootApplication Developer Tools 关于 Developer Tools 的一些细节 原 ...

  5. 剑指offer13:数组[奇数,偶数],奇数偶数相对位置不变。

    1. 题目描述 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变. 2. 思路和方 ...

  6. C++根据用户输入打印对应的金层塔层数

    #include <iostream> #include <Windows.h> using namespace std; int main(void) { int row; ...

  7. PAT(B) 1062 最简分数(Java)

    题目链接:1062 最简分数 (20 point(s)) 题目描述 一个分数一般写成两个整数相除的形式:N/M,其中 M 不为0.最简分数是指分子和分母没有公约数的分数表示形式. 现给定两个不相等的正 ...

  8. 微信小程序的页面跳转==编程式导航传参 和 标签的方法传参==以及如何过去传递过来的参数

    小程序导航传参接收传递过来的参数 在onload中 实例

  9. sidecar-inject代码分析

    Istio通过对serviceMesh中的每个pod注入sidecar,来实现无侵入式的服务治理能力.其中,sidecar的注入是其能力实现的重要一环(本文主要介绍在kubernetes集群中的注入方 ...

  10. Centos 安装PHP-redis扩展

    从https://pecl.php.net/package/redis   里面找到自己安装的Redis对应版本的redis 1.获取已经安装的Redis版本扩展我这边安装的是4.0.1版本 wget ...