Tuesday, June 7, 2011

Inheritance and subclassing in Go - or its near likeness


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.


11 comments:

  1. very good ! I'm very pleased to discover how to make Inheritance in GO :-)

    ReplyDelete
  2. Thanks for this writeup... super helpful!

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Is there some way to pass a Ferrari to something that is expecting a Car as an argument? I haven't figured out a syntax for that yet!

    ReplyDelete
    Replies
    1. Yes, there is. Please check the post titled "Interfaces in Go" in the table of contents. (http://golangtutorials.blogspot.com/2011/06/interfaces-in-go.html)

      Delete
  5. How would this work when the functions are attached to pointers of the types instead of the types themselves? Would I need to instantiate it like `&AstonMartin{&Car{4}}` ?

    ReplyDelete
    Replies
    1. Go resolves pointers and instances automatically when it comes to member access and function calling. So if struct A has a member function F, and 'a' is an instance of it, then a.F(); p:=&a; p.F(); are ok.

      For types (like variables or struct member variables) you will need to explicitly ensure that you use the & and * appropriately to get the correct type.

      Delete
  6. Nice article, was wondering how go implements inheritance(extends like in Java).

    ReplyDelete
  7. Nice post about Inheritance in java .
    thanks you very much for this useful post.

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete

If you think others also will find these tutorials useful, kindly "+1" it above and mention the link in your own blogs, responses, and entries on the net so that others also may reach here. Thank you.

Note: Only a member of this blog may post a comment.