Inheritance/Single: Difference between revisions

add E example
(WP-style note about implementation inheritance)
(add E example)
Line 126:
// ...
}</lang>
 
=={{header|E}}==
 
Outside of interactions with the host platform's objects, E does not generally deal in complex type hierarchies; the focus is more on "what guarantees does this object provide", and composition rather than inheritance. However, it is possible to set up a type hierarchy scheme with just a bit of code.
 
In E, a ''guard'' accepts, or coerces, certain objects and rejects others; its [[wp:Range (mathematics)|range]] constitutes a type. An ''auditor'' examines the implementation of an object and marks it approved; a ''stamp'' is an auditor which does no actual checking. Here, we create a guard/stamp pair; the guard accepts every stamped object. The stamp also asks for each supertype's stamp on the objects it audits.
 
<lang e>def makeType(label, superstamps) {
def stamp {
to audit(audition) {
for s in superstamps { audition.ask(s) }
return true
}
}
def guard {
to coerce(specimen, ejector) {
if (__auditedBy(stamp, specimen)) {
return specimen
} else {
throw.eject(ejector, `$specimen is not a $label`)
}
}
}
return [guard, stamp]
}</lang>
 
Setting up the task's specified tree:
 
<lang e>def [Animal, AnimalStamp] := makeType("Animal", [])
 
def [Cat, CatStamp] := makeType("Cat", [AnimalStamp])
def [Dog, DogStamp] := makeType("Dog", [AnimalStamp])
 
def [Lab, LabStamp] := makeType("Lab", [DogStamp])
def [Collie, CollieStamp] := makeType("Collie", [DogStamp])</lang>
 
Some example objects:
 
<lang e>def fido implements LabStamp {}
def tom implements CatStamp {}
def brick {} # not an animal</lang>
 
Testing against the types:
 
<lang e>? fido :Animal
# value: <fido>
 
? fido :Cat
# problem: <fido> is not a Cat
 
? fido :Lab
# value: <fido>
 
? tom :Animal
# value: <tom>
 
? tom :Cat
# value: <tom>
 
? brick :Animal
# problem: <brick> is not a Animal</lang>
 
=={{header|Groovy}}==