Inheritance/Single: Difference between revisions
Content deleted Content added
No edit summary |
PascalABC.NET |
||
(53 intermediate revisions by 24 users not shown) | |||
Line 3:
[[Category:Type System]]
[[Category:Encyclopedia]]
::: ''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
:::* 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.
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]].
;Task:
Show a tree of types which inherit from each other.
::: At 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 <br> (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}}
<syntaxhighlight lang="11l">T Animal
{
}
T Dog(Animal)
{
}
T Cat(Animal)
{
}
T Lab(Dog)
{
}
T Collie(Dog)
{
}</syntaxhighlight>
=={{header|ActionScript}}==
<syntaxhighlight lang
public class Animal {
// ...
}
// ...
}
// ...
}
// ...
}
// ...
}</
=={{header|Ada}}==
<
type Animal is tagged private;
type Dog is new Animal with private;
Line 60 ⟶ 114:
type Lab is new Dog with null record;
type Collie is new Dog with null record;
end Inheritance;</
=={{header|Aikido}}==
<syntaxhighlight lang
class Animal{
//functions go here...
}
//functions go here...
}
//functions go here...
}
//functions go here...
}
//functions go here...
}
</syntaxhighlight>
=={{header|AmigaE}}==
<
OBJECT animal
ENDOBJECT
Line 95 ⟶ 151:
OBJECT collie OF dog
ENDOBJECT
</syntaxhighlight>
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">script Animal
end script
script Dog
property parent : Animal
end script
script Cat
property parent : Animal
end script
script Lab
property parent : Dog
end script
script Collie
property parent : Dog
end script</syntaxhighlight>
=={{header|AutoHotkey}}==
Line 101 ⟶ 178:
AutoHotkey_L is prototype-based. However, for convenience, class-syntax may be used to create a base object.
<
MsgBox, % "A " dog.__Class " is a " dog.base.base.__Class " and is part of the " dog.kingdom " kingdom."
Line 114 ⟶ 191:
}
class Collie extends Dog {
}</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
DIM Animal{method}
Line 137 ⟶ 214:
DIM Collie{method}
PROC_inherit(Collie{}, Dog{})
PROC_class(Collie{})</
=={{header|C}}==
* See [[Inheritance/C]]
=={{header|
<syntaxhighlight lang
{
/* ... */
// ...
}
class Dog : Animal
{
/* ... */
// ...
}
class Lab : Dog
{
/* ... */
// ...
}
class Collie : Dog
{
/* ... */
// ...
}
class Cat : Animal
{
/* ... */
// ...
}</syntaxhighlight>
=={{header|C++}}==
<
{
// ...
Line 183 ⟶ 274:
{
// ...
};</
=={{header|
<syntaxhighlight lang="chuck">
public class Drums{
/
}
public class LatinKit extends Drums{
//functions go here...
}
public class ElectronicKit extends Drums{
//functions go here...
}
public class Congas extends LatinKit{
//functions go here...
}
public class TechnoDrums extends ElectronicKit{
//functions go here...
}
</syntaxhighlight>
=={{header|Clojure}}==
Line 220 ⟶ 299:
This is not very useful in clojure
<
(gen-class :name Dog :extends Animal)
(gen-class :name Cat :extends Animal)
(gen-class :name Lab :extends Dog)
(gen-class :name Collie :extends Dog)</
More useful:
<
(derive ::cat ::animal)
(derive ::lab ::dog)
(derive ::collie ::dog)</
use:
<
true
user> (isa? ::dog ::cat)
false
user> (isa? ::collie ::animal)
true</
=={{header|COBOL}}==
<
CLASS-ID. Animal.
*> ...
END CLASS Animal.
CLASS-ID. Dog
INHERITS FROM Animal.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
Line 256 ⟶ 338:
END CLASS Dog.
CLASS-ID. Cat
INHERITS FROM Animal.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
Line 265 ⟶ 349:
END CLASS Cat.
CLASS-ID. Lab
INHERITS FROM Dog.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
Line 274 ⟶ 360:
END CLASS Lab.
CLASS-ID. Collie
INHERITS FROM Dog.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
Line 281 ⟶ 369:
*> ...
END CLASS Collie.</
=={{header|Coco}}==
<
class Cat extends Animal
class Dog extends Animal
class Lab extends Dog
class Collie extends Dog</
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:
<
(@name) ->
Line 320 ⟶ 408:
sam.move!
tom.move!</
=={{header|Comal}}==
{{works with|UniComal}}
{{works with|AmiComal}}
<
DIM Species$ OF 20
ENDSTRUC Animal
Line 357 ⟶ 445:
Race$:="Collie"
ENDFUNC New
ENDSTRUC Collie</
==
Using CLOS classes, we have the following:
<
(defclass dog (animal) ())
(defclass lab (dog) ())
(defclass collie (dog) ())
(defclass cat (animal) ())</
Alternatively, since there is no multiple inheritance in the task requirement, structures could also be used:
<
(defstruct (dog (:include animal)))
(defstruct (lab (:include dog)))
(defstruct (collie (:include dog)))
(defstruct (cat (:include animal)))</
(Structures are less flexible than CLOS objects but often somewhat more efficiently implemented, due to those restrictions.)
Line 383 ⟶ 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.
<
;;; ASN.1 serialization logic specialized for animal class
(defmethod serialize-to-asn-1 ((a animal))
Line 392 ⟶ 480:
(defmethod serialize-to-asn-1 ((s string))
#| ... #|
)</
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.
==
<
TYPE
Animal = ABSTRACT RECORD (* *) END;
Line 405 ⟶ 493:
Lab = RECORD (Dog) (* *) END;
Collie = RECORD (Dog) (* *) END;
</syntaxhighlight>
=={{header|D}}==
<
// ...
}
Line 428 ⟶ 516:
}
void main() {}</
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">type
Animal = class(TObject)
private
Line 443 ⟶ 531:
Cat = class(Animal);
Collie = class(Dog);
Lab = class(Dog);</
=={{header|DWScript}}==
<syntaxhighlight lang="delphi">type
Animal = class(TObject)
private
Line 458 ⟶ 546:
type Cat = class(Animal) end;
type Collie = class(Dog) end;
type Lab = class(Dog) end;</
=={{header|E}}==
Line 466 ⟶ 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.
<
def stamp {
to audit(audition) {
Line 483 ⟶ 571:
}
return [guard, stamp]
}</
Setting up the task's specified tree:
<
def [Cat, CatStamp] := makeType("Cat", [AnimalStamp])
Line 493 ⟶ 581:
def [Lab, LabStamp] := makeType("Lab", [DogStamp])
def [Collie, CollieStamp] := makeType("Collie", [DogStamp])</
Some example objects:
<
def tom implements CatStamp {}
def brick {} # not an animal</
Testing against the types:
<
# value: <fido>
Line 519 ⟶ 607:
? brick :Animal
# problem: <brick> is not a Animal</
=={{header|Eiffel}}==
<
class
ANIMAL
end
DOG
inherit
ANIMAL
end
CAT
inherit
ANIMAL
end
LAB
inherit
DOG
end
COLLIE
inherit
DOG
end
</syntaxhighlight>
=={{header|Elena}}==
ELENA 4.x :
<
{
// ...
}
class Dog
{
// ...
}
class Lab
{
// ...
}
class Collie
{
// ...
}
class Cat
{
// ...
}</syntaxhighlight>
=={{header|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.
<syntaxhighlight lang="fsharp">type Animal() =
class // explicit syntax needed for empty class
end
type Dog() =
inherit Animal()
type Lab() =
inherit Dog()
type Collie() =
inherit Dog()
type Cat() =
inherit Animal()</syntaxhighlight>
=={{header|Factor}}==
<
TUPLE: dog < animal ;
TUPLE: cat < animal ;
TUPLE: lab < dog ;
TUPLE: collie < dog ;</
=={{header|Fancy}}==
<
# ...
}
Line 599 ⟶ 735:
class Collie : Dog {
# ...
}</
=={{header|Fantom}}==
<
{
}
Line 620 ⟶ 756:
class Collie : Dog
{
}</
=={{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]].
<
:: Animal class end-class {} ;
Line 631 ⟶ 767:
:: Cat extends Animal end-extends {} ;
:: Lab extends Dog end-extends {} ;
:: Collie extends Dog end-extends {} ;</
Works with any ANS Forth
Needs the
https://github.com/DouglasBHoffman/FMS2
<
:class Animal ;class
Line 644 ⟶ 780:
:class Cat <super Animal ;class
:class Lab <super Dog ;class
:class Collie <super Dog ;class</
=={{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).
<
type animal
Line 666 ⟶ 802:
end type collie
end module anim</
=={{header|FreeBASIC}}==
<
Type Animal Extends Object ' to enable virtual methods etc. if needed
Line 689 ⟶ 825:
Type Collie Extends Dog
' ...
End Type</
=={{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.
<
type animal struct {
Line 743 ⟶ 861:
pet.color = "yellow"
}
</syntaxhighlight>
=={{header|Groovy}}==
<syntaxhighlight lang
class Animal{
//contents go here...
}
//contents go here...
}
//contents go here...
}
//contents go here...
}
//contents go here...
}
</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.
<
class Animal a => Cat a
class Animal a => Dog a
class Dog a => Lab a
class Dog a => Collie a</
=={{header|Haxe}}==
<syntaxhighlight lang
class Animal {
// ...
}
// ...
}
// ...
}
// ...
}
// ...
}
</syntaxhighlight>
== Icon and {{header|Unicon}} ==
Line 792 ⟶ 914:
This example only works in Unicon.
<syntaxhighlight lang="unicon">
class Animal ()
end
Line 807 ⟶ 929:
class Collie : Dog ()
end
</syntaxhighlight>
=={{header|Inform 7}}==
<
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.</
"Animal" is actually a predefined kind in Inform 7, so its definition here is redundant (but legal).
Line 820 ⟶ 942:
=={{header|Io}}==
<
Cat := Animal clone
Dog := Animal clone
Collie := Dog clone
Lab := Dog clone</
=={{header|J}}==
Line 830 ⟶ 952:
Here is how this would normally be done:
<syntaxhighlight lang="j">
coclass 'Dog'
coinsert 'Animal'
coclass 'Cat'
coinsert 'Animal'
coclass 'Lab'
coinsert 'Dog'
coclass 'Collie'
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 846 ⟶ 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:
<
coinsert_Cat_ 'Animal'
coinsert_Lab_ 'Dog'
coinsert_Collie_ 'Dog'</
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
public class Animal{
//functions go here...
}
//functions go here...
}
//functions go here...
}
//functions go here...
}
//functions go here...
}
</syntaxhighlight>
=={{header|JavaScript}}==
JavaScript is a class-free, object-oriented language, and as such, it uses prototypal inheritance instead of classical inheritance.
<syntaxhighlight lang
function Animal() {
// ...
}
// ...
}
Dog.prototype = new Animal();
// ...
}
Cat.prototype = new Animal();
// ...
}
Collie.prototype = new Dog();
// ...
}
Lab.prototype = new Dog();
var lab = new Lab();
lab.speak(); // shows "an animal makes a sound"
</syntaxhighlight>
=={{header|Julia}}==
Julia is not really an object-oriented programming language. It
<
abstract type Animal end
abstract type Dog <: Animal end
Line 910 ⟶ 1,038:
struct Lab <: Dog end
struct Collie <: Dog end
</syntaxhighlight>
=={{header|Kite}}==
<
#Method goes here
];
Line 928 ⟶ 1,056:
#Method goes here
];
</syntaxhighlight>
=={{header|Kotlin}}==
<
open class Animal {
Line 962 ⟶ 1,090:
println("Bella is a $bella")
println("Casey is a $casey")
}</
{{out}}
Line 971 ⟶ 1,099:
Casey is a collie
</pre>
=={{header|Lasso}}==
<
data public gender::string
}
Line 997 ⟶ 1,124:
#myanimal -> gender = 'Male'
#myanimal -> gender</
-> Male
=={{header|Latitude}}==
Latitude is a prototype-oriented language, so defining a subclass is equivalent to constructing an instance.
<syntaxhighlight lang="latitude">
Animal ::= Object clone tap {
;; Methods go here...
}.
Dog ::= Animal clone tap {
;; Methods go here...
}.
Cat ::= Animal clone tap {
;; Methods go here...
}.
Lab ::= Dog clone tap {
;; Methods go here...
}.
Collie ::= Dog clone tap {
;; Methods go here...
}.</syntaxhighlight>
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".
=={{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">
-- parent script "Animal"
-- ...
property ancestor
Line 1,011 ⟶ 1,166:
me.ancestor = script("Animal").new()
return me
end
property ancestor
Line 1,019 ⟶ 1,174:
me.ancestor = script("Animal").new()
return me
end
property ancestor
Line 1,027 ⟶ 1,182:
me.ancestor = script("Dog").new()
return me
end
property ancestor
Line 1,035 ⟶ 1,190:
me.ancestor = script("Dog").new()
return me
end
</syntaxhighlight>
=={{header|Lisaac}}==
<syntaxhighlight lang="lisaac">
Section Header
+ name := ANIMAL;
// ...
+ name := CAT;
Section Inherit
- parent : ANIMAL := ANIMAL;
// ...
+ name := DOG;
Section Inherit
- parent : ANIMAL := ANIMAL;
// ...
+ name := LAB;
Section Inherit
- parent : DOG := DOG;
// ...
+ name := COLLIE;
Section Inherit
- parent : DOG := DOG;
// ...
</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).
<
:- object(thing,
instantiates(thing)).
Line 1,092 ⟶ 1,250:
specializes(dog)).
...
:- end_object.</
=={{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>
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Class Animal {
}
Class Dog as Animal {
}
Class Cat as Animal{
}
Class
}
Class Collie As Dog{
}
\\ a is a pointer to a group made from class Labrador
a->Labrador()
Print a is type Animal = True
Print a is type Labrador = True
}
CheckIt
</syntaxhighlight>
=={{header|Neko}}==
<
var Dog = $new(null);
Line 1,174 ⟶ 1,333:
var Collie = $new(null);
$objsetproto(Collie, Dog);</
=={{header|Nemerle}}==
<
// ...
}
Line 1,194 ⟶ 1,354:
class Cat: Animal {
// ...
}</
=={{header|NetRexx}}==
Line 1,200 ⟶ 1,360:
For brevity, all classes are defined within the same source file. Normally classes exist as separate source units.
<
options replace format comments java crossref symbols binary
Line 1,255 ⟶ 1,415:
-- Do Collie specific set-up
return
</syntaxhighlight>
{{out}}
<pre>
Line 1,268 ⟶ 1,428:
=={{header|Nim}}==
<
Animal = object of RootObj
Dog = object of Animal
Cat = object of Animal
Lab = object of Dog
Collie = object of Dog</
=={{header|Oberon}}==
Tested with [https://miasap.se/obnc OBNC].
<syntaxhighlight lang="oberon">MODULE Animals;
TYPE
Animal = RECORD END;
Dog = RECORD (Animal) END;
Cat = RECORD (Animal) END;
Lab = RECORD (Dog) END;
Collie = RECORD (Dog) END;
END Animals.
</syntaxhighlight>
=={{header|Oberon-2}}==
Works with oo2c Version 2
<
MODULE Animals;
TYPE
Animal = POINTER TO AnimalDesc;
AnimalDesc = RECORD
Cat = POINTER TO CatDesc;
Line 1,296 ⟶ 1,470:
END Animals.
</syntaxhighlight>
=={{header|Objeck}}==
<
{ #~ ... ~# }
Line 1,312 ⟶ 1,486:
class Cat from Animal
{ #~ ... ~# }</
=={{header|Objective-C}}==
<
{
// ...
Line 1,348 ⟶ 1,522:
}
// ...
@end</
=={{header|OCaml}}==
<syntaxhighlight lang
class animal =
object (self)
(*functions go here...*)
end
object (self)
inherit animal
(*functions go here...*)
end
object (self)
inherit animal
(*functions go here...*)
end
object (self)
inherit dog
(*functions go here...*)
end
object (self)
inherit dog
(*functions go here...*)
end
</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}}==
<
Animal Class new: Cat
Animal Class new: Dog
Dog Class new: Lab
Dog Class new: Collie</
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
-- subclass of object by default
::class animal
Line 1,397 ⟶ 1,608:
::class collie subclass dog
</syntaxhighlight>
=={{header|OxygenBasic}}==
<
class animal
method show() as string
Line 1,409 ⟶ 1,619:
class dog
from
method show() as string
return animal.show()+"dog "
Line 1,416 ⟶ 1,626:
class cat
from
method show() as string
return animal.show()+"cat "
Line 1,423 ⟶ 1,633:
class Lab
from
method show() as string
return dog.show()+"Lab "
Line 1,430 ⟶ 1,640:
class Collie
from
method show() as string
return dog.show()+"Collie "
Line 1,439 ⟶ 1,649:
Collie c
print c.show 'result: Animal Dog Collie
</syntaxhighlight>
=={{header|Oz}}==
<
%% ...
end
Line 1,460 ⟶ 1,670:
class Cat from Animal
%% ...
end</
=={{header|Pascal}}==
See [[Inheritance/Single#Delphi | Delphi]]
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
type
Animal = class end;
Dog = class(Animal) end;
Cat = class(Animal) end;
Lab = class(Dog) end;
Collie = class(Dog) end;
</syntaxhighlight>
=={{header|Perl}}==
<syntaxhighlight lang
package Animal;
#functions go here...
1;
use Animal;
@ISA = qw( Animal );
#functions go here...
1;
use Animal;
@ISA = qw( Animal );
#functions go here...
1;
use Dog;
@ISA = qw( Dog );
#functions go here...
1;
use Dog;
@ISA = qw( Dog );
#functions go here...
1;
# The same using the [http://search.cpan.org/perldoc?MooseX::Declare MooseX::Declare] module:
class Animal {
Line 1,513 ⟶ 1,735:
class Collie extends Dog {
# methods go here...
}
</syntaxhighlight>
=={{header|
{{libheader|Phix/Class}}
Add (private|public) fields and methods as needed. Make Animal and Dog abstract (ie use "abstract class") to prevent instantiation.
<!--(notonline)-->
<syntaxhighlight lang="phix">
without js -- (class)
class
private string species
end class
class Dog extends Animal
public procedure bark()
puts(1,"woof\n")
end procedure
end class
class Lab extends Dog end class
class Collie extends Dog end class
class Cat extends Animal end class
</syntaxhighlight>
=={{header|PHP}}==
<
// functions go here...
}
Line 1,551 ⟶ 1,776:
class Collie extends Dog {
// functions go here...
}</
=={{header|PicoLisp}}==
<
(class +Dog +Animal)
Line 1,562 ⟶ 1,787:
(class +Lab +Dog)
(class +Collie +Dog)</
<
+Animal
+Cat
+Dog
+Collie
+Lab</
=={{header|PowerShell}}==
{{works with|PowerShell|5}}
<syntaxhighlight lang="powershell">
class Animal {}
class Dog : Animal {}
Line 1,578 ⟶ 1,803:
class Lab : Dog {}
class Collie : Dog {}
</syntaxhighlight>
=={{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===
<
Eat()
Sleep()
Line 1,603 ⟶ 1,828:
Interface Collie Extends Dog
HeardSheep()
EndInterface</
===Simple OOP Version===
Using the open-source precompiler [http://www.development-lounge.de/viewtopic.php?t=5915 SimpleOOP].
<
EndClass
Line 1,632 ⟶ 1,857:
*Lassie.Collie = NewObject.Collie
*Lassie\Bark()
*Lassie\Fetch()</
=={{header|Python}}==
Unrevised style classes:
<
pass #functions go here...
Line 1,649 ⟶ 1,874:
class Collie(Dog):
pass #functions go here...</
New style classes:
<
class Animal(object):
Line 1,698 ⟶ 1,923:
buddy = Labrador()
buddy.kill()
print
</syntaxhighlight>
{{out}}
<pre>
Line 1,707 ⟶ 1,933:
===S3===
Inheritance is implemented by setting the object's class attribute with a character vector.
<
class(aCollie) <- c("Collie", "Dog", "Animal")</
===S4===
Inheritance is implemented by using the 'contains' argument in setClass
<
setClass("Dog", representation(), prototype(), contains="Animal")
setClass("Cat", representation(), prototype(), contains="Animal")
setClass("Collie", representation(), prototype(), contains="Dog")
setClass("Lab", representation(), prototype(), contains="Dog")</
=={{header|Racket}}==
<
#lang racket
Line 1,733 ⟶ 1,959:
(check-true (is-a? (new dog%) animal%))
(check-false (is-a? (new collie%) cat%))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015-09-16}}
<syntaxhighlight lang="raku" line>class Animal {}
class Dog is Animal {}
class Cat is Animal {}
class Lab is Dog {}
class Collie is Dog {}
say Collie.^parents; # undefined type object
say Collie.new.^parents; # instantiated object</syntaxhighlight>
{{out}}
<pre>((Dog) (Animal))
((Dog) (Animal))</pre>
The <tt>.^parents</tt> notation indicates a method call to the object's metaobject rather than to the object itself.
=={{header|REBOL}}==
<
Title: "Inheritance"
URL: http://rosettacode.org/wiki/Inheritance
]
Line 1,763 ⟶ 2,005:
print ["Cat has" Cat/legs "legs."]
print ["Lab says:" Lab/says]</
{{out}}
Line 1,770 ⟶ 2,012:
=={{header|Ring}}==
<
Class Animal
Class Dog from Animal
Line 1,776 ⟶ 2,018:
Class Lab from Dog
Class Collie from Dog
</syntaxhighlight>
=={{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).
<
#functions go here...
def self.inherited(subclass)
Line 1,801 ⟶ 2,043:
class Collie < Dog
#functions go here...
end</
{{out}}
Line 1,808 ⟶ 2,050:
new subclass of Dog: Collie
new subclass of Animal: Cat</pre>
=={{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.
<syntaxhighlight lang="rust">trait Animal {}
trait Cat: Animal {}
trait Dog: Animal {}
trait Lab: Dog {}
trait Collie: Dog {}</syntaxhighlight>
=={{header|Scala}}==
Line 1,818 ⟶ 2,068:
any (or all) of the <code>class</code> keywords below can be replaced with <code>trait</code>
<
class Dog extends Animal
class Cat extends Animal
class Lab extends Dog
class Collie extends Dog</
=={{header|Seed7}}==
Line 1,828 ⟶ 2,078:
The example below defines a hierarchy of implementation types.
<
const type: Animal is new struct
Line 1,848 ⟶ 2,098:
const type: Cat is sub Animal struct
# ...
end struct;</
=={{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
animal = ()
collie = (| parent* = dog |)
</syntaxhighlight>
=={{header|Sidef}}==
<
class Dog << Animal {};
class Cat << Animal {};
class Lab << Dog {};
class Collie << Dog {};</
=={{header|Simula}}==
<
class Animal;
Line 1,891 ⟶ 2,142:
end;
end</
=={{header|Slate}}==
<
define: #Dog &parents: {Animal}.
define: #Cat &parents: {Animal}.
define: #Lab &parents: {Dog}.
define: #Collie &parents: {Dog}.</
=={{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.
<
instanceVariableNames: ' ' "* space separated list of names *"
classVariableNames: ' '
Line 1,924 ⟶ 2,175:
!Dog subclass: #Collie
"* etc. *" !</
=={{header|Swift}}==
<
// ...
}
Line 1,945 ⟶ 2,196:
class Cat : Animal {
// ...
}</
=={{header|Tcl}}==
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<
oo::class create Animal {
# ...
Line 1,968 ⟶ 2,219:
superclass Dog
# ...
}</
=={{header|TXR}}==
Line 1,974 ⟶ 2,225:
====Inheritance among symbolic exception tags====
<
@(defex lab dog animal)
@(defex collie dog)</
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 1,982 ⟶ 2,233:
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:
<
@ (throw lab "x")
@(catch animal (arg))
@(end)</
{{out}} Test:
Line 1,993 ⟶ 2,244:
====OOP Inheritance in TXR Lisp====
<
name
(:method get-name (me)
Line 2,015 ⟶ 2,266:
(pet2 (new cat name "Max")))
pet1.(speak)
pet2.(speak))</
{{out}}
Line 2,023 ⟶ 2,274:
=={{header|Visual Basic .NET}}==
<
' ...
End Class
Line 2,045 ⟶ 2,296:
Inherits Animal
' ...
End Class</
=={{header|Vorpal}}==
<
cat = new(pet)
dog = new(pet)
fido = new(dog)
felix = new(cat)</
=={{header|Wren}}==
<syntaxhighlight lang="wren">class Animal {
// methods
}
class Dog is Animal {
// methods
}
class Cat is Animal {
// mwethods
}
class Labrador is Dog {
// methods
}
class Collie is Dog {
// methods
}</syntaxhighlight>
=={{header|XLISP}}==
<
(define-class dog
Line 2,067 ⟶ 2,339:
(define-class lab
(super-class dog))</
A REPL session:
<
#<Class:ANIMAL #x57094c8>
Line 2,089 ⟶ 2,361:
IVARCNT = 0
IVARTOTAL = 0
#<Class:DOG #x57094c8></
=={{header|zkl}}==
<
class Dog(Animal){} class Cat(Animal){}
class Lab(Dog){} class Collie(Dog){}
Collie.linearizeParents</
{{out}}
<pre>
Line 2,101 ⟶ 2,373:
</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,115 ⟶ 2,392:
{{Omit From|TI-83 BASIC}}
{{Omit From|TI-89 BASIC}}
{{omit from|Z80 Assembly}}
|