Inheritance/Single: Difference between revisions

m
 
(31 intermediate revisions by 12 users not shown)
Line 3:
[[Category:Type System]]
[[Category:Encyclopedia]]
:''This task is about derived types; for implementation inheritance, see [[Polymorphism]].
 
::: ''This task is about derived types;   for implementation inheritance, see [[Polymorphism]].
Inheritance is an operation of [[type algebra]] that creates a new type from one or several parent types. The obtained type is called '''derived type'''. It inherits some of the properties of its parent types. Usually inherited properties are:
 
* methods
 
* components
Inheritance is an operation of [[type algebra]] that creates a new type from one or several parent types.
* parts of the representation
 
The [[classes | class]] of the new type is a '''subclass''' of the classes rooted in the parent types. When all (in certain sense) properties of the parents are preserved by the derived type, it is said to be a [[wp:Liskov_substitution_principle|Liskov subtype]]. When properties are preserved then the derived type is ''substitutable'' for its parents in all contexts. Usually full substitutability is achievable only in some contexts.
The obtained type is called '''derived type'''.
 
It inherits some of the properties of its parent types.
 
Usually inherited properties are:
:::*   methods
:::*   components
:::*   parts of the representation
 
 
The [[classes | class]] of the new type is a   '''subclass'''   of the classes rooted in the parent types.
 
When all (in certain sense) properties of the parents are preserved by the derived type,   it is said to be a [[wp:Liskov_substitution_principle|Liskov subtype]].
 
When properties are preserved then the derived type is ''substitutable'' for its parents in all contexts.   Usually full substitutability is achievable only in some contexts.
 
 
Inheritance is
:::*   '''single''', when only one parent is allowed
:::*   '''[[multiple inheritance | multiple]]''', otherwise
 
 
Some single inheritance languages usually allow multiple inheritance for certain [[abstract type]]s, interfaces in particular.
 
Inheritance can be considered as a relation parent-child.
Inheritance can be considered as a relation parent-child. Parent types are sometimes called '''supertype''', the derived ones are '''subtype'''. This relation is [[wp:Transitive_relation|transitive]] and [[wp:Reflexive_relation|reflexive]]. Types bound by the relation form a [[wp:Directed_acyclic_graph directed acyclic graph]] (ignoring reflexivity). With single inheritance it becomes a [[wp:Tree_(graph_theory)|tree]].
 
Parent types are sometimes called '''supertype''', the derived ones are '''subtype'''.   This relation is [[wp:Transitive_relation|transitive]] and [[wp:Reflexive_relation|reflexive]].
'''Task''': Show a tree of types which inherit from each other. The top of the tree should be a class called Animal. The second level should have Dog and Cat. Under Dog should be Lab and Collie. None of the classes need to have any functions, the only thing they need to do is inherit from the specified superclasses (overriding functions should be shown in [[Polymorphism]]). The tree should look like this:
 
<pre> Animal
Types bound by the relation form a [[wp:Directed_acyclic_graph directed acyclic graph]] (ignoring reflexivity).
/\
 
/ \
With single inheritance it becomes a [[wp:Tree_(graph_theory)|tree]].
/ \
 
Dog Cat
 
/\
;Task:
/ \
Show a tree of types which inherit from each other.
/ \
::: &nbsp; At the top of the tree should be a class called &nbsp; '''Animal'''.
Lab Collie</pre>
::: &nbsp; The second level should have '''Dog''' and '''Cat'''.
::: &nbsp; Under &nbsp; '''Dog''' &nbsp; should be &nbsp; '''Lab''' &nbsp; and &nbsp; '''Collie'''.
::: &nbsp; None of the classes need to have any functions, &nbsp; the only thing they need to do is inherit from the specified superclasses <br> &nbsp; (overriding functions should be shown in [[Polymorphism]]).
 
 
The tree should look like this:
<pre>
Animal
/\
/ \
/ \
Dog Cat
/\
/ \
/ \
Lab Collie
</pre>
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">T Animal
{
}
Line 47 ⟶ 81:
T Collie(Dog)
{
}</langsyntaxhighlight>
 
=={{header|ActionScript}}==
<syntaxhighlight lang ="actionscript">public class Animal {
public class Animal {
// ...
}
}</lang>
<lang actionscript>public class Cat extends Animal {
// ...
}
}</lang>
<lang actionscript>public class Dog extends Animal {
// ...
}
}</lang>
<lang actionscript>public class Lab extends Dog {
// ...
}
}</lang>
<lang actionscript>public class Collie extends Dog {
// ...
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">package Inheritance is
type Animal is tagged private;
type Dog is new Animal with private;
Line 79 ⟶ 114:
type Lab is new Dog with null record;
type Collie is new Dog with null record;
end Inheritance;</langsyntaxhighlight>
 
=={{header|Aikido}}==
<syntaxhighlight lang ="aikido ">class Animal{
class Animal{
//functions go here...
}
}</lang>
<lang aikido >class Dog extends Animal {
//functions go here...
}
}</lang>
<lang aikido >class Cat extends Animal {
//functions go here...
}
}</lang>
<lang aikido >class Lab extends Dog {
//functions go here...
}
}</lang>
<lang aikido >class Collie extends Dog {
//functions go here...
}
}</lang>
</syntaxhighlight>
 
=={{header|AmigaE}}==
<langsyntaxhighlight lang="amigae">
OBJECT animal
ENDOBJECT
Line 114 ⟶ 151:
OBJECT collie OF dog
ENDOBJECT
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
 
<langsyntaxhighlight lang="applescript">script Animal
end script
 
Line 135 ⟶ 172:
script Collie
property parent : Dog
end script</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
Line 141 ⟶ 178:
 
AutoHotkey_L is prototype-based. However, for convenience, class-syntax may be used to create a base object.
<langsyntaxhighlight AutoHotkeylang="autohotkey">dog := new Collie
MsgBox, % "A " dog.__Class " is a " dog.base.base.__Class " and is part of the " dog.kingdom " kingdom."
 
Line 154 ⟶ 191:
}
class Collie extends Dog {
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"CLASSLIB"
DIM Animal{method}
Line 177 ⟶ 214:
DIM Collie{method}
PROC_inherit(Collie{}, Dog{})
PROC_class(Collie{})</langsyntaxhighlight>
 
=={{header|C}}==
Line 183 ⟶ 220:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">class Animal
{
/* ... */
Line 211 ⟶ 248:
/* ... */
// ...
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">class Animal
{
// ...
Line 237 ⟶ 274:
{
// ...
};</langsyntaxhighlight>
 
=={{header|ChucK}}==
<syntaxhighlight lang="chuck">
<lang ChucK>public class Drums{
public class Drums{
//functions go here...
}
}</lang>
<lang ChucK>public class LatinKit extends Drums{
//functions go here...
}
}</lang>
<lang ChucK>public class ElectronicKit extends Drums{
//functions go here...
}
}</lang>
<lang ChucK>public class Congas extends LatinKit{
//functions go here...
}
}</lang>
<lang ChucK>public class TechnoDrums extends ElectronicKit{
//functions go here...
}
}</lang>
</syntaxhighlight>
 
=={{header|Clojure}}==
Line 260 ⟶ 299:
This is not very useful in clojure
 
<langsyntaxhighlight Clojurelang="clojure">(gen-class :name Animal)
(gen-class :name Dog :extends Animal)
(gen-class :name Cat :extends Animal)
(gen-class :name Lab :extends Dog)
(gen-class :name Collie :extends Dog)</langsyntaxhighlight>
 
More useful:
 
<langsyntaxhighlight Clojurelang="clojure">(derive ::dog ::animal)
(derive ::cat ::animal)
(derive ::lab ::dog)
(derive ::collie ::dog)</langsyntaxhighlight>
 
use:
 
<langsyntaxhighlight Clojurelang="clojure">user> (isa? ::dog ::animal)
true
user> (isa? ::dog ::cat)
false
user> (isa? ::collie ::animal)
true</langsyntaxhighlight>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> CLASS-ID.IDENTIFICATION AnimalDIVISION.
CLASS-ID. Animal.
*> ...
END CLASS Animal.
CLASS-ID.IDENTIFICATION Dog INHERITS AnimalDIVISION.
CLASS-ID. Dog
INHERITS FROM Animal.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
Line 296 ⟶ 338:
END CLASS Dog.
CLASS-ID.IDENTIFICATION Cat INHERITS AnimalDIVISION.
CLASS-ID. Cat
INHERITS FROM Animal.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
Line 305 ⟶ 349:
END CLASS Cat.
CLASS-ID.IDENTIFICATION Lab INHERITS DogDIVISION.
CLASS-ID. Lab
INHERITS FROM Dog.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
Line 314 ⟶ 360:
END CLASS Lab.
CLASS-ID.IDENTIFICATION Collie INHERITS DogDIVISION.
CLASS-ID. Collie
INHERITS FROM Dog.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
Line 321 ⟶ 369:
 
*> ...
END CLASS Collie.</langsyntaxhighlight>
 
=={{header|Coco}}==
 
<langsyntaxhighlight lang="coco">class Animal
class Cat extends Animal
class Dog extends Animal
class Lab extends Dog
class Collie extends Dog</langsyntaxhighlight>
 
On the subject of inheritance, it is worth noting that Coco's <code>super</code> works differently from CoffeeScript's. In particular, the constructor of a subclass should generally say <code>super ...</code>, not just <code>super</code>. Here is a translation of the example from the CoffeeScript documentation:
 
<langsyntaxhighlight lang="coco">class Animal
 
(@name) ->
Line 360 ⟶ 408:
 
sam.move!
tom.move!</langsyntaxhighlight>
 
=={{header|Comal}}==
{{works with|UniComal}}
{{works with|AmiComal}}
<langsyntaxhighlight Comallang="comal"> STRUC Animal
DIM Species$ OF 20
ENDSTRUC Animal
Line 397 ⟶ 445:
Race$:="Collie"
ENDFUNC New
ENDSTRUC Collie</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 403 ⟶ 451:
Using CLOS classes, we have the following:
 
<langsyntaxhighlight lang="lisp">(defclass animal () ())
(defclass dog (animal) ())
(defclass lab (dog) ())
(defclass collie (dog) ())
(defclass cat (animal) ())</langsyntaxhighlight>
 
Alternatively, since there is no multiple inheritance in the task requirement, structures could also be used:
 
<langsyntaxhighlight lang="lisp">(defstruct animal)
(defstruct (dog (:include animal)))
(defstruct (lab (:include dog)))
(defstruct (collie (:include dog)))
(defstruct (cat (:include animal)))</langsyntaxhighlight>
 
(Structures are less flexible than CLOS objects but often somewhat more efficiently implemented, due to those restrictions.)
Line 423 ⟶ 471:
Furthermore, all of the "basic types" also have a class, so methods can be readily specialized to lists, integers, strings, symbols, et cetera. This is done without having to modify any class definitions.
 
<langsyntaxhighlight lang="lisp">
;;; ASN.1 serialization logic specialized for animal class
(defmethod serialize-to-asn-1 ((a animal))
Line 432 ⟶ 480:
(defmethod serialize-to-asn-1 ((s string))
#| ... #|
)</langsyntaxhighlight>
 
These classes do not have to inherit from some interface or base class which provides a prototype for the serialize-to-asn-1 method. Such a requirement has more to do with static typing than object oriented programming. Usually in languages which require such inheritance, there are also statically typed references. A class must conform to some "ASNEncodable" class so that its instances can be passed to functions which expect references to an ASN1Encodable type, which is verified at compile time.
Line 438 ⟶ 486:
=={{header|Component Pascal}}==
 
<langsyntaxhighlight lang="oberon2">
TYPE
Animal = ABSTRACT RECORD (* *) END;
Line 445 ⟶ 493:
Lab = RECORD (Dog) (* *) END;
Collie = RECORD (Dog) (* *) END;
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">class Animal {
// ...
}
Line 468 ⟶ 516:
}
 
void main() {}</langsyntaxhighlight>
 
=={{header|Delphi}}==
 
<syntaxhighlight lang="delphi">type
<lang Delphi>type
Animal = class(TObject)
private
Line 483 ⟶ 531:
Cat = class(Animal);
Collie = class(Dog);
Lab = class(Dog);</langsyntaxhighlight>
 
=={{header|DWScript}}==
 
<syntaxhighlight lang="delphi">type
<lang Delphi>type
Animal = class(TObject)
private
Line 498 ⟶ 546:
type Cat = class(Animal) end;
type Collie = class(Dog) end;
type Lab = class(Dog) end;</langsyntaxhighlight>
 
=={{header|E}}==
Line 506 ⟶ 554:
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.
 
<langsyntaxhighlight lang="e">def makeType(label, superstamps) {
def stamp {
to audit(audition) {
Line 523 ⟶ 571:
}
return [guard, stamp]
}</langsyntaxhighlight>
 
Setting up the task's specified tree:
 
<langsyntaxhighlight lang="e">def [Animal, AnimalStamp] := makeType("Animal", [])
 
def [Cat, CatStamp] := makeType("Cat", [AnimalStamp])
Line 533 ⟶ 581:
 
def [Lab, LabStamp] := makeType("Lab", [DogStamp])
def [Collie, CollieStamp] := makeType("Collie", [DogStamp])</langsyntaxhighlight>
 
Some example objects:
 
<langsyntaxhighlight lang="e">def fido implements LabStamp {}
def tom implements CatStamp {}
def brick {} # not an animal</langsyntaxhighlight>
 
Testing against the types:
 
<langsyntaxhighlight lang="e">? fido :Animal
# value: <fido>
 
Line 559 ⟶ 607:
 
? brick :Animal
# problem: <brick> is not a Animal</langsyntaxhighlight>
 
=={{header|Eiffel}}==
<langsyntaxhighlight lang="eiffel ">class
class
ANIMAL
end</lang>
<lang eiffel >class
DOG
inherit
ANIMAL
end</lang>
<lang eiffel >class
CAT
inherit
ANIMAL
end</lang>
<lang eiffel >class
LAB
inherit
DOG
end</lang>
<lang eiffel >class
COLLIE
inherit
DOG
end</lang>
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x :
<langsyntaxhighlight lang="elena">class Animal
{
// ...
Line 611 ⟶ 661:
{
// ...
}</langsyntaxhighlight>
 
=={{header|F#EMal}}==
<syntaxhighlight lang="emal">
in Org:RosettaCode
type Animal
model do end
type Dog extends Animal
model do end
type Cat extends Animal
model do end
type Lab extends Dog
model do end
type Collie extends Dog
model do end
type Main
var fuffy = Collie()
for each generic kind in generic[Animal, Dog, Cat, Lab, Collie]
writeLine("Fuffy " + when(Generic.check(kind, fuffy), "is", "is not") + " a " + Generic.name(kind))
end
</syntaxhighlight>
{{out}}
<pre>
Fuffy is a Org:RosettaCode:Animal
Fuffy is a Org:RosettaCode:Dog
Fuffy is not a Org:RosettaCode:Cat
Fuffy is not a Org:RosettaCode:Lab
Fuffy is a Org:RosettaCode:Collie
</pre>
 
=={{header|F_Sharp|F#}}==
The <code>()</code> behind the class names indicates a public default constructor; you need some type of public constructor to derive from a class.
<langsyntaxhighlight lang="fsharp">type Animal() =
class // explicit syntax needed for empty class
end
Line 629 ⟶ 707:
 
type Cat() =
inherit Animal()</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">TUPLE: animal ;
TUPLE: dog < animal ;
TUPLE: cat < animal ;
TUPLE: lab < dog ;
TUPLE: collie < dog ;</langsyntaxhighlight>
 
=={{header|Fancy}}==
<langsyntaxhighlight lang="fancy">class Animal {
# ...
}
Line 657 ⟶ 735:
class Collie : Dog {
# ...
}</langsyntaxhighlight>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">class Animal
{
}
Line 678 ⟶ 756:
class Collie : Dog
{
}</langsyntaxhighlight>
 
=={{header|Forth}}==
{{works with|4tH|3.61.5}}
There are numerous, mutually incompatible object oriented frameworks for Forth. This one works with the FOOS preprocessor extension of [[4tH]].
<langsyntaxhighlight lang="forth">include 4pp/lib/foos.4pp
 
:: Animal class end-class {} ;
Line 689 ⟶ 767:
:: Cat extends Animal end-extends {} ;
:: Lab extends Dog end-extends {} ;
:: Collie extends Dog end-extends {} ;</langsyntaxhighlight>
 
 
Line 696 ⟶ 774:
Needs the FMS2 library code located here:
https://github.com/DouglasBHoffman/FMS2
<langsyntaxhighlight lang="forth">include FMS2LL.f
 
:class Animal ;class
Line 702 ⟶ 780:
:class Cat <super Animal ;class
:class Lab <super Dog ;class
:class Collie <super Dog ;class</langsyntaxhighlight>
 
=={{header|Fortran}}==
OO has been part of the Fortran standard since 2003 but the compilers are still playing catchup. This example builds with the Intel 11.1.069 compiler (free for personal use on linux).
 
<langsyntaxhighlight lang="fortran">module anim
 
type animal
Line 724 ⟶ 802:
end type collie
 
end module anim</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type Animal Extends Object ' to enable virtual methods etc. if needed
Line 747 ⟶ 825:
Type Collie Extends Dog
' ...
End Type</langsyntaxhighlight>
 
=={{header|Go}}==
Go eschews most trappings of inheritance, yet it's anonymous field feature allows building one struct type upon another and accessing fields of "embedded" types without extra synax.
<langsyntaxhighlight lang="go">package main
 
type animal struct {
Line 783 ⟶ 861:
pet.color = "yellow"
}
</syntaxhighlight>
</lang>
 
=={{header|Groovy}}==
<syntaxhighlight lang ="groovy">class Animal{
class Animal{
//contents go here...
}
}</lang>
<lang groovy>class Dog extends Animal{
//contents go here...
}
}</lang>
<lang groovy>class Cat extends Animal{
//contents go here...
}
}</lang>
<lang groovy>class Lab extends Dog{
//contents go here...
}
}</lang>
<lang groovy>class Collie extends Dog{
//contents go here...
}
}</lang>
</syntaxhighlight>
 
=={{header|Haskell}}==
A type can't inherit properties from other types, but it can belong to any number of type classes, which may themselves be subclasses of other type classes.
 
<langsyntaxhighlight lang="haskell">class Animal a
class Animal a => Cat a
class Animal a => Dog a
class Dog a => Lab a
class Dog a => Collie a</langsyntaxhighlight>
 
=={{header|Haxe}}==
<syntaxhighlight lang ="haxe">class Animal {
class Animal {
// ...
}
}</lang>
<lang haxe>class Cat extends Animal {
// ...
}
}</lang>
<lang haxe>class Dog extends Animal {
// ...
}
}</lang>
<lang haxe>class Lab extends Dog {
// ...
}
}</lang>
<lang haxe>class Collie extends Dog {
// ...
}
}</lang>
</syntaxhighlight>
 
== Icon and {{header|Unicon}} ==
Line 832 ⟶ 914:
This example only works in Unicon.
 
<syntaxhighlight lang="unicon">
<lang Unicon>
class Animal ()
end
Line 847 ⟶ 929:
class Collie : Dog ()
end
</syntaxhighlight>
</lang>
 
=={{header|Inform 7}}==
<langsyntaxhighlight lang="inform7">An animal is a kind of thing.
A cat is a kind of animal.
A dog is a kind of animal.
A collie is a kind of dog.
A lab is a kind of dog.</langsyntaxhighlight>
 
"Animal" is actually a predefined kind in Inform 7, so its definition here is redundant (but legal).
Line 860 ⟶ 942:
=={{header|Io}}==
 
<langsyntaxhighlight lang="io">Animal := Object clone
Cat := Animal clone
Dog := Animal clone
Collie := Dog clone
Lab := Dog clone</langsyntaxhighlight>
 
=={{header|J}}==
Line 870 ⟶ 952:
Here is how this would normally be done:
 
<syntaxhighlight lang="j">
<lang j>coclass 'Animal'</lang>
<lang j>coclass 'DogAnimal'
coclass 'Dog'
coinsert 'Animal'</lang>
coinsert 'Animal'
<lang j>coclass 'Cat'
coclass 'Cat'
coinsert 'Animal'</lang>
coinsert 'Animal'
<lang j>coclass 'Lab'
coclass 'Lab'
coinsert 'Dog'</lang>
coinsert 'Dog'
<lang j>coclass 'Collie'
coclass 'Collie'
coinsert 'Dog'</lang>
coinsert 'Dog'
</syntaxhighlight>
 
<code>coclass</code> specifies that following definitions will be within the named class, and <code>coinsert</code> specifies that the current class will inherit from the named classes (or object -- in J the only difference between a class and an object is its name and how you can create them -- this motivates the "co" prefix on operations which manipulate '''c'''lasses and '''o'''bjects).
Line 886 ⟶ 970:
That said, some operations in J -- including <code>coinsert</code> -- will create classes if they did not already exist. So the above may be simplified to:
 
<langsyntaxhighlight lang="j">coinsert_Dog_ 'Animal'
coinsert_Cat_ 'Animal'
coinsert_Lab_ 'Dog'
coinsert_Collie_ 'Dog'</langsyntaxhighlight>
 
That said, note that classes and objects are not "types" in J. Instead, they are components of names. In general, when we deal with objects and classes we deal with references to the underlying representation, and in J the references are names, so a collection of classes and objects, in J, would be a collection of names which refer to classes and objects. In other words, the "type" (to the degree that there is a type) would be best thought of as "name" (or, more mechanically: boxed list of characters).
 
=={{header|Java}}==
<syntaxhighlight lang ="java">public class Animal{
public class Animal{
//functions go here...
}
}</lang>
<lang java>public class Dog extends Animal{
//functions go here...
}
}</lang>
<lang java>public class Cat extends Animal{
//functions go here...
}
}</lang>
<lang java>public class Lab extends Dog{
//functions go here...
}
}</lang>
<lang java>public class Collie extends Dog{
//functions go here...
}
}</lang>
</syntaxhighlight>
 
=={{header|JavaScript}}==
JavaScript is a class-free, object-oriented language, and as such, it uses prototypal inheritance instead of classical inheritance.
<syntaxhighlight lang ="javascript">function Animal() {
function Animal() {
// ...
}
}</lang>
 
<lang javascript>function Dog() {
// ...
}
Dog.prototype = new Animal();</lang>
 
<lang javascript>function Cat() {
// ...
}
Cat.prototype = new Animal();</lang>
 
<lang javascript>function Collie() {
// ...
}
Collie.prototype = new Dog();</lang>
 
<lang javascript>function Lab() {
// ...
}
Lab.prototype = new Dog();</lang>
 
<lang javascript>Animal.prototype.speak = function() {print("an animal makes a sound")};
 
var lab = new Lab();
lab.speak(); // shows "an animal makes a sound"</lang>
</syntaxhighlight>
 
=={{header|Julia}}==
Julia is not really an object-oriented programming language. It supports polymorphism and inheriting functionality but not structure. Thus inheritance hierarchies must be made with abstract types. Abstract types can not be instantiated and do not contain any fields. So below Dog is abstract while Collie is a concrete type which may contain fields.
<langsyntaxhighlight lang="julia">
abstract type Animal end
abstract type Dog <: Animal end
Line 950 ⟶ 1,038:
struct Lab <: Dog end
struct Collie <: Dog end
</syntaxhighlight>
</lang>
 
=={{header|Kite}}==
<langsyntaxhighlight Kitelang="kite">class Animal [
#Method goes here
];
Line 968 ⟶ 1,056:
#Method goes here
];
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
open class Animal {
Line 1,002 ⟶ 1,090:
println("Bella is a $bella")
println("Casey is a $casey")
}</langsyntaxhighlight>
 
{{out}}
Line 1,013 ⟶ 1,101:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define animal => type {
data public gender::string
}
Line 1,036 ⟶ 1,124:
 
#myanimal -> gender = 'Male'
#myanimal -> gender</langsyntaxhighlight>
-> Male
 
Line 1,043 ⟶ 1,131:
Latitude is a prototype-oriented language, so defining a subclass is equivalent to constructing an instance.
 
<langsyntaxhighlight lang="latitude">
Animal ::= Object clone tap {
;; Methods go here...
Line 1,062 ⟶ 1,150:
Collie ::= Dog clone tap {
;; Methods go here...
}.</langsyntaxhighlight>
 
We <code>clone</code> the parent and then <code>tap</code> the new instance to add functionality to it. Note that we use <code>::=</code> here rather than the usual <code>:=</code>, as the former implicitly defines an appropriate <code>toString</code> method representative of the new "class".
Line 1,068 ⟶ 1,156:
=={{header|Lingo}}==
In Lingo Classes are represented by "parent scripts". Instead of using new() as in the code below, child classes can also use rawNew() when creating an instance of their parent classes. rawNew() creates an instance of a class without calling its initialization function 'new' (constructor).
<syntaxhighlight lang="lingo">
<lang lingo>-- parent script "Animal"
-- parent script "Animal"
-- ...</lang>
-- ...
 
<lang lingo>-- parent script "Dog"
property ancestor
 
Line 1,077 ⟶ 1,166:
me.ancestor = script("Animal").new()
return me
end</lang>
<lang lingo>-- parent script "Cat"
property ancestor
 
Line 1,085 ⟶ 1,174:
me.ancestor = script("Animal").new()
return me
end</lang>
 
<lang lingo>-- parent script "Lab"
property ancestor
 
Line 1,093 ⟶ 1,182:
me.ancestor = script("Dog").new()
return me
end</lang>
 
<lang lingo>-- parent script "Collie"
property ancestor
 
Line 1,101 ⟶ 1,190:
me.ancestor = script("Dog").new()
return me
end</lang>
</syntaxhighlight>
 
=={{header|Lisaac}}==
<syntaxhighlight lang="lisaac">
<lang Lisaac>Section Header
Section Header
+ name := ANIMAL;
// ...</lang>
<lang Lisaac>Section Header
+ name := CAT;
Section Inherit
- parent : ANIMAL := ANIMAL;
// ...</lang>
<lang Lisaac>Section Header
+ name := DOG;
Section Inherit
- parent : ANIMAL := ANIMAL;
// ...</lang>
<lang Lisaac>Section Header
+ name := LAB;
Section Inherit
- parent : DOG := DOG;
// ...</lang>
<lang Lisaac>Section Header
+ name := COLLIE;
Section Inherit
- parent : DOG := DOG;
// ...</lang>
</syntaxhighlight>
 
=={{header|Logtalk}}==
There is no "class" keyword in Logtalk; an "object" keyword is used instead (Logtalk objects play the role of classes, meta-classes, instances, or prototypes depending on the relations with other objects).
<langsyntaxhighlight lang="logtalk">
:- object(thing,
instantiates(thing)).
Line 1,158 ⟶ 1,250:
specializes(dog)).
...
:- end_object.</langsyntaxhighlight>
 
=={{header|Lua}}==
Lua has no in-built formal OOP mechanism, though there are many possible ways of implementing work-alikes.
<syntaxhighlight lang="lua">Class = {
classname = "Class aka Object aka Root-Of-Tree",
new = function(s,t)
s.__index = s
local instance = setmetatable(t or {}, s)
instance.parent = s
return instance
end
}
 
Animal = Class:new{classname="Animal", speak=function(s) return s.voice or "("..s.classname.." has no voice)" end }
Cat = Animal:new{classname="Cat", voice="meow"}
Dog = Animal:new{classname="Dog", voice="woof"}
Lab = Dog:new{classname="Lab", voice="bark"}
Collie = Dog:new{classname="Collie"} -- subclass without a unique voice
 
print("Animal:speak(): " .. Animal:speak())
print("Cat:speak(): " .. Cat:speak())
print("Dog:speak(): " .. Dog:speak())
print("Lab:speak(): " .. Lab:speak())
print("Collie:speak(): " .. Collie:speak())
 
max = Collie:new{voice="Hi, I am Max the talking Collie!"} -- instance with a unique voice
print("max:speak(): " .. max:speak())
print("max himself is (instance): " .. max.classname)
print("max's parent is (class): " .. max.parent.classname)
print("max's parent's parent is (class): " .. max.parent.parent.classname)
print("max's parent's parent's parent is (class): " .. max.parent.parent.parent.classname)
print("max's parent's parent's parent's parent is (class): " .. max.parent.parent.parent.parent.classname)
print("max's parent's parent's parent's parent's parent is (nil reference): " .. tostring(max.parent.parent.parent.parent.parent))</syntaxhighlight>
{{out}}
<pre>Animal:speak(): (Animal has no voice)
Cat:speak(): meow
Dog:speak(): woof
Lab:speak(): bark
Collie:speak(): woof
max:speak(): Hi, I am Max the talking Collie!
max himself is (instance): Collie
max's parent is (class): Collie
max's parent's parent is (class): Dog
max's parent's parent's parent is (class): Animal
max's parent's parent's parent's parent is (class): Class aka Object aka Root-Of-Tree
max's parent's parent's parent's parent's parent is (nil reference): nil</pre>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Class Animal {
Line 1,180 ⟶ 1,318:
}
CheckIt
</syntaxhighlight>
</lang>
 
=={{header|Neko}}==
<langsyntaxhighlight Nekolang="neko">var Animal = $new(null);
 
var Dog = $new(null);
Line 1,195 ⟶ 1,333:
 
var Collie = $new(null);
$objsetproto(Collie, Dog);</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight lang="nemerle">class Animal {
// ...
}
Line 1,216 ⟶ 1,354:
class Cat: Animal {
// ...
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
Line 1,222 ⟶ 1,360:
 
For brevity, all classes are defined within the same source file. Normally classes exist as separate source units.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 1,277 ⟶ 1,415:
-- Do Collie specific set-up
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,290 ⟶ 1,428:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">type
Animal = object of RootObj
Dog = object of Animal
Cat = object of Animal
Lab = object of Dog
Collie = object of Dog</langsyntaxhighlight>
 
=={{header|Oberon}}==
Tested with [https://miasap.se/obnc OBNC].
<langsyntaxhighlight Oberonlang="oberon">MODULE Animals;
 
TYPE
Line 1,309 ⟶ 1,447:
 
END Animals.
</syntaxhighlight>
</lang>
 
=={{header|Oberon-2}}==
Works with oo2c Version 2
<langsyntaxhighlight lang="oberon2">
MODULE Animals;
TYPE
Line 1,332 ⟶ 1,470:
 
END Animals.
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class Animal
{ #~ ... ~# }
Line 1,348 ⟶ 1,486:
class Cat from Animal
{ #~ ... ~# }</langsyntaxhighlight>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">@interface Animal : NSObject
{
// ...
Line 1,384 ⟶ 1,522:
}
// ...
@end</langsyntaxhighlight>
 
=={{header|OCaml}}==
<syntaxhighlight lang ="ocaml">class animal =
class animal =
object (self)
(*functions go here...*)
end</lang>
<lang ocaml>class dog =
object (self)
inherit animal
(*functions go here...*)
end</lang>
<lang ocaml>class cat =
object (self)
inherit animal
(*functions go here...*)
end</lang>
<lang ocaml>class lab =
object (self)
inherit dog
(*functions go here...*)
end</lang>
<lang ocaml>class collie =
object (self)
inherit dog
(*functions go here...*)
end</lang>
</syntaxhighlight>
 
=={{header|Odin}}==
 
<syntaxhighlight lang="odin">package main
 
Animal :: struct {
alive: bool
}
 
Dog :: struct {
using animal: Animal,
obedience_trained: bool
}
 
Cat :: struct {
using animal: Animal,
litterbox_trained: bool
}
 
Lab :: struct {
using dog: Dog,
color: string
}
 
Collie :: struct {
using dog: Dog,
catches_frisbee: bool
}
 
main :: proc() {
pet : Lab
 
pet.alive = true
pet.obedience_trained = true
pet.color = "yellow"
}</syntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">Object Class new: Animal
Animal Class new: Cat
Animal Class new: Dog
Dog Class new: Lab
Dog Class new: Collie</langsyntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
-- subclass of object by default
::class animal
Line 1,432 ⟶ 1,608:
 
::class collie subclass dog
</syntaxhighlight>
</lang>
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
class animal
method show() as string
Line 1,443 ⟶ 1,619:
 
class dog
from Animal Animal
method show() as string
return animal.show()+"dog "
Line 1,450 ⟶ 1,626:
 
class cat
from animal animal
method show() as string
return animal.show()+"cat "
Line 1,457 ⟶ 1,633:
 
class Lab
from dog dog
method show() as string
return dog.show()+"Lab "
Line 1,464 ⟶ 1,640:
 
class Collie
from dog dog
method show() as string
return dog.show()+"Collie "
Line 1,473 ⟶ 1,649:
Collie c
print c.show 'result: Animal Dog Collie
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">class Animal
%% ...
end
Line 1,494 ⟶ 1,670:
class Cat from Animal
%% ...
end</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,501 ⟶ 1,677:
=={{header|Perl}}==
 
<syntaxhighlight lang ="perl">package Animal;
package Animal;
#functions go here...
1;</lang>
 
<lang perl>package Dog;
use Animal;
@ISA = qw( Animal );
#functions go here...
1;</lang>
 
<lang perl>package Cat;
use Animal;
@ISA = qw( Animal );
#functions go here...
1;</lang>
 
<lang perl>package Lab;
use Dog;
@ISA = qw( Dog );
#functions go here...
1;</lang>
 
<lang perl>package Collie;
use Dog;
@ISA = qw( Dog );
#functions go here...
1;</lang>
 
# The same using the [http://search.cpan.org/perldoc?MooseX::Declare MooseX::Declare] module:
 
<lang perl>use MooseX::Declare;
 
class Animal {
Line 1,547 ⟶ 1,724:
class Collie extends Dog {
# methods go here...
}
}</lang>
</syntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/Class}}
Add (private|public) fields and methods as needed. Make Animal and Dog abstract (ie use "abstract class") to prevent instantiation.
<!--(notonline)-->
Needs 0.8.1+
<syntaxhighlight lang="phix">
<lang Phix>class Animal
without js -- (class)
class Animal
private string species
end class
Line 1,563 ⟶ 1,743:
class Lab extends Dog end class
class Collie extends Dog end class
class Cat extends Animal end class</lang>
</syntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">class Animal {
// functions go here...
}
Line 1,584 ⟶ 1,765:
class Collie extends Dog {
// functions go here...
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(class +Animal)
 
(class +Dog +Animal)
Line 1,595 ⟶ 1,776:
(class +Lab +Dog)
 
(class +Collie +Dog)</langsyntaxhighlight>
<langsyntaxhighlight PicoLisplang="picolisp">: (dep '+Animal)
+Animal
+Cat
+Dog
+Collie
+Lab</langsyntaxhighlight>
 
=={{header|PowerShell}}==
{{works with|PowerShell|5}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
class Animal {}
class Dog : Animal {}
Line 1,611 ⟶ 1,792:
class Lab : Dog {}
class Collie : Dog {}
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
Although PureBasic is mostly used for procedural coding it has both the ability to interact with object oriented libraries and code and also the capacity to write it if needed.
===Native version===
<langsyntaxhighlight PureBasiclang="purebasic">Interface Animal
Eat()
Sleep()
Line 1,636 ⟶ 1,817:
Interface Collie Extends Dog
HeardSheep()
EndInterface</langsyntaxhighlight>
===Simple OOP Version===
Using the open-source precompiler [http://www.development-lounge.de/viewtopic.php?t=5915 SimpleOOP].
<langsyntaxhighlight PureBasiclang="purebasic">Class Animal
EndClass
 
Line 1,665 ⟶ 1,846:
*Lassie.Collie = NewObject.Collie
*Lassie\Bark()
*Lassie\Fetch()</langsyntaxhighlight>
 
=={{header|Python}}==
Unrevised style classes:
<langsyntaxhighlight lang="python">class Animal:
pass #functions go here...
 
Line 1,682 ⟶ 1,863:
 
class Collie(Dog):
pass #functions go here...</langsyntaxhighlight>
 
New style classes:
<langsyntaxhighlight lang="python">import time
 
class Animal(object):
Line 1,731 ⟶ 1,912:
buddy = Labrador()
buddy.kill()
print (f"Felix has", {felix.lives,} "lives, ","Buddy is %salive!"%(""{'not' if buddy.alive else "'not'} alive!")</lang>
</syntaxhighlight>
{{out}}
<pre>
Line 1,740 ⟶ 1,922:
===S3===
Inheritance is implemented by setting the object's class attribute with a character vector.
<langsyntaxhighlight Rlang="r">aCollie <- "woof"
class(aCollie) <- c("Collie", "Dog", "Animal")</langsyntaxhighlight>
===S4===
Inheritance is implemented by using the 'contains' argument in setClass
<langsyntaxhighlight Rlang="r">setClass("Animal", representation(), prototype())
setClass("Dog", representation(), prototype(), contains="Animal")
setClass("Cat", representation(), prototype(), contains="Animal")
setClass("Collie", representation(), prototype(), contains="Dog")
setClass("Lab", representation(), prototype(), contains="Dog")</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 1,766 ⟶ 1,948:
(check-true (is-a? (new dog%) animal%))
(check-false (is-a? (new collie%) cat%))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 1,772 ⟶ 1,954:
 
{{works with|Rakudo|2015-09-16}}
<syntaxhighlight lang="raku" perl6line>class Animal {}
class Dog is Animal {}
class Cat is Animal {}
Line 1,779 ⟶ 1,961:
 
say Collie.^parents; # undefined type object
say Collie.new.^parents; # instantiated object</langsyntaxhighlight>
{{out}}
<pre>((Dog) (Animal))
Line 1,787 ⟶ 1,969:
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Inheritance"
URL: http://rosettacode.org/wiki/Inheritance
Line 1,812 ⟶ 1,994:
print ["Cat has" Cat/legs "legs."]
 
print ["Lab says:" Lab/says]</langsyntaxhighlight>
 
{{out}}
Line 1,819 ⟶ 2,001:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
Class Animal
Class Dog from Animal
Line 1,825 ⟶ 2,007:
Class Lab from Dog
Class Collie from Dog
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<code>inherited</code> is a method defined on an instance of a <code>Class</code> object. It is invoked when a new subclass of the current class is defined (i.e. at the <code>end</code> statement of a <code>class</code> definition).
<langsyntaxhighlight lang="ruby">class Animal
#functions go here...
def self.inherited(subclass)
Line 1,850 ⟶ 2,032:
class Collie < Dog
#functions go here...
end</langsyntaxhighlight>
 
{{out}}
Line 1,860 ⟶ 2,042:
=={{header|Rust}}==
A type can't inherit properties from other types, but it can implmement any number of traits, which may themselves be subtraits of other traits.
<langsyntaxhighlight Rustlang="rust">trait Animal {}
trait Cat: Animal {}
trait Dog: Animal {}
trait Lab: Dog {}
trait Collie: Dog {}</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 1,875 ⟶ 2,057:
any (or all) of the <code>class</code> keywords below can be replaced with <code>trait</code>
 
<langsyntaxhighlight lang="scala">class Animal
class Dog extends Animal
class Cat extends Animal
class Lab extends Dog
class Collie extends Dog</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 1,885 ⟶ 2,067:
The example below defines a hierarchy of implementation types.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: Animal is new struct
Line 1,905 ⟶ 2,087:
const type: Cat is sub Animal struct
# ...
end struct;</langsyntaxhighlight>
 
=={{header|Self}}==
Self is a class-free, object-oriented language, and as such, it uses prototypal inheritance instead of classical inheritance. This is an example of the relevant excerpts from a Self transporter fileout. Normally the object tree would be built and navigated within the graphical Self environment.
<syntaxhighlight lang ="self>animal = ()</lang">
animal = ()
<lang self>dog = (| parent* = animal |)</lang>
<lang self>catdog = (| parent* = animal |)</lang>
<lang self>labcat = (| parent* = doganimal |)</lang>
<lang self>collielab = (| parent* = dog |)</lang>
collie = (| parent* = dog |)
</syntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">class Animal {};
class Dog << Animal {};
class Cat << Animal {};
class Lab << Dog {};
class Collie << Dog {};</langsyntaxhighlight>
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">begin
 
class Animal;
Line 1,947 ⟶ 2,131:
end;
 
end</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">define: #Animal &parents: {Cloneable}.
define: #Dog &parents: {Animal}.
define: #Cat &parents: {Animal}.
define: #Lab &parents: {Dog}.
define: #Collie &parents: {Dog}.</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
This is an example of the object serialization format used by many varieties of Smalltalk. Normally the class tree would be defined and navigated via a class browser within a graphical Smalltalk environment.
<langsyntaxhighlight lang="smalltalk">Object subclass: #Animal
instanceVariableNames: ' ' "* space separated list of names *"
classVariableNames: ' '
Line 1,980 ⟶ 2,164:
 
!Dog subclass: #Collie
"* etc. *" !</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">class Animal {
// ...
}
Line 2,001 ⟶ 2,185:
class Cat : Animal {
// ...
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<langsyntaxhighlight lang="tcl">package require TclOO
oo::class create Animal {
# ...
Line 2,024 ⟶ 2,208:
superclass Dog
# ...
}</langsyntaxhighlight>
 
=={{header|TXR}}==
Line 2,030 ⟶ 2,214:
====Inheritance among symbolic exception tags====
 
<langsyntaxhighlight lang="txr">@(defex cat animal)
@(defex lab dog animal)
@(defex collie dog)</langsyntaxhighlight>
 
The second line is a shorthand which defines a lab to be a kind of dog, and at the same time a dog to be a kind of animal.
Line 2,038 ⟶ 2,222:
If we throw an exception of type <code>lab</code>, it can be caught in a catch for a <code>dog</code> or for an <code>animal</code>. Continuing with the query:
 
<langsyntaxhighlight lang="txr">@(try)
@ (throw lab "x")
@(catch animal (arg))
@(end)</langsyntaxhighlight>
 
{{out}} Test:
Line 2,049 ⟶ 2,233:
====OOP Inheritance in TXR Lisp====
 
<langsyntaxhighlight lang="txrlisp">(defstruct animal nil
name
(:method get-name (me)
Line 2,071 ⟶ 2,255:
(pet2 (new cat name "Max")))
pet1.(speak)
pet2.(speak))</langsyntaxhighlight>
 
{{out}}
Line 2,079 ⟶ 2,263:
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Class Animal
' ...
End Class
Line 2,101 ⟶ 2,285:
Inherits Animal
' ...
End Class</langsyntaxhighlight>
 
=={{header|Vorpal}}==
<langsyntaxhighlight lang="vorpal">pet = new()
cat = new(pet)
dog = new(pet)
fido = new(dog)
felix = new(cat)</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">class Animal {
// methods
}
Line 2,129 ⟶ 2,313:
class Collie is Dog {
// methods
}</langsyntaxhighlight>
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="lisp">(define-class animal)
 
(define-class dog
Line 2,144 ⟶ 2,328:
 
(define-class lab
(super-class dog))</langsyntaxhighlight>
A REPL session:
<langsyntaxhighlight lang="lisp">[1] (cat 'superclass)
 
#<Class:ANIMAL #x57094c8>
Line 2,166 ⟶ 2,350:
IVARCNT = 0
IVARTOTAL = 0
#<Class:DOG #x57094c8></langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">class Animal{}
class Dog(Animal){} class Cat(Animal){}
class Lab(Dog){} class Collie(Dog){}
Collie.linearizeParents</langsyntaxhighlight>
{{out}}
<pre>
Line 2,178 ⟶ 2,362:
</pre>
 
{{omit from|6502 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|8080 Assembly}}
{{omit from|8086 Assembly}}
{{Omit From|ALGOL 68|It isn't immediately obvious that ALGOL 68 is object oriented.}}
{{omit from|ARM Assembly}}
{{Omit From|AWK}}
{{omit from|Axe}}
Line 2,192 ⟶ 2,381:
{{Omit From|TI-83 BASIC}}
{{Omit From|TI-89 BASIC}}
{{omit from|Z80 Assembly}}
7,794

edits