Sealed classes and methods: Difference between revisions

Added Go
m (julia example)
(Added Go)
Line 63:
Lisa is watching the movie...
Sorry, Fred, you are too young to watch the movie.</pre>
 
=={{header|Go}}==
Go isn't really an object oriented language - not in a conventional sense anyway.
 
It has structs rather than classes which are just a collection of fields. It does however have methods which are declared outside the struct itself but within the same package and whose receiver is either a struct instance or a pointer to one. Non-struct types can also have methods though this isn't relevant here.
 
As a general rule, all entities are accessible within the same package but are only accessible to other packages if their name begins with an upper case letter.
 
Inheritance is not supported but can be simulated to some extent by embedding one struct inside another. The latter is then able to access the former's fields directly and to call its methods.
 
Consequently, a Go struct and its methods are effectively sealed unless the struct is embedded in another one. However, the only way to prevent embedding from outside the package would be to make the struct private to its package which may not be an acceptable solution unless it and/or its methods could be exposed indirectly.
 
The Wren approach isn't feasible because, as the following example shows, the parent method always thinks its receiver is a parent even though it may be a child!
 
We can still prevent 'Fred' from watching the movie on age grounds though the code needed to do this would prevent an under age parent from watching the movie as well.
<syntaxhighlight lang="go">package main
 
import "fmt"
 
type parent struct {
name string
age int
}
 
type child struct {
parent // embedded struct
}
 
func (p parent) watchMovie() {
fmt.Printf("The type of %s is %T\n", p.name, p)
if p.age < 15 {
fmt.Printf("Sorry, %s, you are too young to watch the movie.\n", p.name)
} else {
fmt.Printf("%s is watching the movie...\n", p.name)
}
}
 
func main() {
p := parent{"Donald", 42}
p.watchMovie()
c1 := child{parent{"Lisa", 18}}
c2 := child{parent{"Fred", 10}}
c1.watchMovie()
c2.watchMovie()
}</syntaxhighlight>
 
{{out}}
<pre>
The type of Donald is main.parent
Donald is watching the movie...
The type of Lisa is main.parent
Lisa is watching the movie...
The type of Fred is main.parent
Sorry, Fred, you are too young to watch the movie.
</pre>
 
=={{header|J}}==
9,482

edits