Abstract type: Difference between revisions

Content added Content deleted
Line 1,104: Line 1,104:


A variable of an interface type can hold a value of any type that implements the methods that are specified in the interface. You don't need to explicitly "declare" that the type "implements" the interface or anything like that -- the compatibility is purely structural based on the methods.
A variable of an interface type can hold a value of any type that implements the methods that are specified in the interface. You don't need to explicitly "declare" that the type "implements" the interface or anything like that -- the compatibility is purely structural based on the methods.

<lang go>package main

import "fmt"

type Beast interface {
Cry() string
}

type Pet struct{}
type Cat struct {
Pet
}

func (p Pet) Name(b Beast) {
fmt.Println(b.Cry())
}
func (p Pet) Cry() string {
return "Woof"
}
func (c Cat) Cry() string {
return "Meow"
}

func main() {
p := Pet{}
c := Cat{}
p.Name(p) // prt Woof
c.Name(c) // prt Meow
}</lang>


=={{header|Groovy}}==
=={{header|Groovy}}==