Last active
February 18, 2019 05:27
-
-
Save gwang/02be27e2a1edde95461e to your computer and use it in GitHub Desktop.
GoLang method inheritance and overridance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
// Method inheritance in GoLang is particularly interesting: | |
// 1. If a struct A has an anonymous field of struct B, then an object of A has all the methods from B. | |
// Yes, that means you can call those methods of B directly without referring the field name, | |
// just as if those methods are native to A. (Refer to the struct Student in the example below.) | |
// 2. This does not work if the field is named though. (Refer to the struct Employee case in the | |
// example below. ) | |
// 3. Then what happens if A has a method whose name overlaps with one of B's methods? | |
// 3.1. A's method takes priority. | |
// 3.2. B's method can be referred by using the type name (since anonymous field) | |
// (Refer to the Customer use case in the example below). | |
type Human struct { | |
name string | |
age int | |
phone string | |
} | |
type Employee struct { | |
who Human | |
company string | |
} | |
type Student struct { | |
Human // anonymous field | |
school string | |
} | |
type Customer struct { | |
Human | |
solute string | |
} | |
// define a method in Human | |
func (h *Human) SayHi() { | |
fmt.Printf("Hi, I am %s you can call me on %s.\n", h.name, h.phone) | |
} | |
func (c *Customer) SayHi() { | |
fmt.Printf("Hi, I am your customer %s %s.\n", c.solute, c.name) | |
} | |
func main() { | |
mark := Student{Human{"Mark", 25, "222-222-YYYY"}, "MIT"} | |
sam := Employee{who: Human{"Sam", 45, "111-888-XXXX"}, company: "Golang Inc"} | |
smith := Customer{Human{"Smith", 30, "806-888-1234"}, "Mrs."} | |
mark.SayHi() | |
sam.who.SayHi() | |
// sam.SayHi() this does not work, compiler error. | |
smith.SayHi() // call SayHi defined for Customer | |
smith.Human.SayHi() // call SayHi defined for Human | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment