Inner classes: Difference between revisions

Added Go
(Added Go)
Line 165:
</pre>
 
 
=={{header|Go}}==
Go supports some aspects of OO albeit in an unorthodox manner:
 
* Structs are used rather than classes.
* Any methods are always defined outside the struct itself but within the containing package.
* Struct fields are never private to the struct itself though, unless they begin with an upper case letter, they are private to the containing package.
* Structs do not support inheritance - composition can be used instead.
* Polymorphism is supported to some extent via the use of interfaces.
 
It is possible to nest structs as the following example shows. However, the problem here is that the nested struct has an anonymous type and the only way to give it methods is via an instance of the Outer struct.
 
In practice it would probably better to declare the nested struct independently but within the same package and achieve encapsulation by restricting the package to those two structs.
<syntaxhighlight lang="go">package main
 
import "fmt"
 
type Outer struct {
field int
Inner struct {
field int
}
}
 
func (o *Outer) outerMethod() {
fmt.Println("Outer's field has a value of", o.field)
}
 
func (o *Outer) innerMethod() {
fmt.Println("Inner's field has a value of", o.Inner.field)
}
 
func main() {
o := &Outer{field: 43}
o.Inner.field = 42
o.innerMethod()
o.outerMethod()
/* alternative but verbose way of instantiating */
p := &Outer{
field: 45,
Inner: struct {
field int
}{
field: 44,
},
}
p.innerMethod()
p.outerMethod()
}</syntaxhighlight>
 
{{out}}
<pre>
Inner's field has a value of 42
Outer's field has a value of 43
Inner's field has a value of 44
Outer's field has a value of 45
</pre>
 
=={{header|J}}==
9,485

edits