fimmtudagur, 26. ágúst 2010

Inheritance in Go

So. You have probably read that Go has no class construct in the language.

What about our grand object oriented design then? How do we implement it?

We can express a hierarchical relationship through composition.

This first code example shows simple inheritance. I know the code is trivial and could be written in a more clever way but that is not the point. It is there to demonstrate subclassing or if you like going from the abstract to the more specific.

Later we will talk about interfaces and see how we can use them to obtain polymorphic behavior.





package main

import "fmt"

// The base thing
type Person struct {
age int
name string
}
func (p *Person) whoAmI() {
fmt.Println("My name is", p.name, "and I am", p.age, "years old")
}

// Derived thing
type Employee struct {
Person // anonymous field (like subclassing)
company string
title string
}
// Override method
func (e *Employee) whoAmI() {
e.Person.whoAmI() // call base
fmt.Println("And I work for", e.company, "as a", e.title)
}
func (e *Employee) work() {
fmt.Println("I'm working")
}

//
type Programmer struct {
Employee
language string
}
func (programmer *Programmer) work() {
fmt.Println("I happen to program in", programmer.language)
}

//
type Manager struct {
Employee
boss bool
}
func (manager *Manager) work() {
fmt.Println("I manage")
if manager.boss {
fmt.Println("and I'm the boss")
}
}

func main() {
donald := &Person{48, "Donald Duck"}
donald.whoAmI()
fmt.Println("------------------------------------")
john := &Employee{Person{23, "John Doe"}, "KoolAid Inc", "Driver"}
john.whoAmI()
john.work()
fmt.Println("------------------------------------")
alice := &Programmer{Employee{Person{30, "Alice in Wonderland"}, "Rabbit Hole Inc", "Senior Developer"}, "Go"}
alice.whoAmI()
alice.work()
fmt.Println("------------------------------------")
bill := &Manager{Employee{Person{55, "William Bar"}, "FooBar Inc", "CxO"}, true}
bill.whoAmI()
bill.work()
}


And the output is

My name is Donald Duck and I am 48 years old
------------------------------------
My name is John Doe and I am 23 years old
And I work for KoolAid Inc as a Driver
I'm working
------------------------------------
My name is Alice in Wonderland and I am 30 years old
And I work for Rabbit Hole Inc as a Senior Developer
I happen to program in Go
------------------------------------
My name is William Bar and I am 55 years old
And I work for FooBar Inc as a CxO
I manage
and I'm the boss


Engin ummæli: