Inheritance/Single
You are encouraged to solve this task according to the task description, using any language you may know.
- 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 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 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, otherwise
Some single inheritance languages usually allow multiple inheritance for certain abstract types, 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 transitive and reflexive. Types bound by the relation form a wp:Directed_acyclic_graph directed acyclic graph (ignoring reflexivity). With single inheritance it becomes a tree.
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:
Animal
/\
/ \
/ \
Dog Cat
/\
/ \
/ \
Lab Collie
[edit] ActionScript
public class Animal {
// ...
}
public class Cat extends Animal {
// ...
}
public class Dog extends Animal {
// ...
}
public class Lab extends Dog {
// ...
}
public class Collie extends Dog {
// ...
}
[edit] Ada
package Inheritance is
type Animal is tagged private;
type Dog is new Animal with private;
type Cat is new Animal with private;
type Lab is new Dog with private;
type Collie is new Dog with private;
private
type Animal is tagged null record;
type Dog is new Animal with null record;
type Cat is new Animal with null record;
type Lab is new Dog with null record;
type Collie is new Dog with null record;
end Inheritance;
[edit] Aikido
class Animal{
//functions go here...
}
class Dog extends Animal {
//functions go here...
}
class Cat extends Animal {
//functions go here...
}
class Lab extends Dog {
//functions go here...
}
class Collie extends Dog {
//functions go here...
}
[edit] AutoHotkey
AutoHotkey_L is prototype-based. However, for convenience, class-syntax may be used to create a base object.
dog := new Collie
MsgBox, % "A " dog.__Class " is a " dog.base.base.__Class " and is part of the " dog.kingdom " kingdom."
class Animal {
static kingdom := "Animalia" ; Class variable
}
class Dog extends Animal {
}
class Cat extends Animal {
}
class Lab extends Dog {
}
class Collie extends Dog {
}
[edit] BBC BASIC
INSTALL @lib$+"CLASSLIB"
DIM Animal{method}
PROC_class(Animal{})
DIM Cat{method}
PROC_inherit(Cat{}, Animal{})
PROC_class(Cat{})
DIM Dog{method}
PROC_inherit(Dog{}, Animal{})
PROC_class(Dog{})
DIM Labrador{method}
PROC_inherit(Labrador{}, Dog{})
PROC_class(Labrador{})
DIM Collie{method}
PROC_inherit(Collie{}, Dog{})
PROC_class(Collie{})
[edit] C
- See Inheritance/C
[edit] C++
class Animal
{
// ...
};
class Dog: public Animal
{
// ...
};
class Lab: public Dog
{
// ...
};
class Collie: public Dog
{
// ...
};
class Cat: public Animal
{
// ...
};
[edit] Clojure
This is not very useful in 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)
More useful:
(derive ::dog ::animal)
(derive ::cat ::animal)
(derive ::lab ::dog)
(derive ::collie ::dog)
use:
user> (isa? ::dog ::animal)
true
user> (isa? ::dog ::cat)
false
user> (isa? ::collie ::animal)
true
[edit] Common Lisp
Using CLOS classes, we have the following:
(defclass animal () ())
(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 animal)
(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.)
Inheritance is not required for object-oriented programming in Lisp. It is used for code reuse, because it allows common utilities and protocol conventions to be factored out into base class methods. However, a class doesn't have to inherit from a base class just so that some existing methods can work with instances of that class.
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))
#| ... |#
)
;;; casually introduce the method over strings too; no relation to animal
(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.
[edit] Component Pascal
TYPE
Animal = ABSTRACT RECORD (* *) END;
Cat = RECORD (Animal) (* *) END; (* final record (cannot be extended) - by default *)
Dog = EXTENSIBLE RECORD (Animal) (* *) END; (* extensible record *)
Lab = RECORD (Dog) (* *) END;
Collie = RECORD (Dog) (* *) END;
[edit] C#
class Animal
{ /* ... */ }
class Dog : Animal
{ /* ... */ }
class Lab : Dog
{ /* ... */ }
class Collie : Dog
{ /* ... */ }
class Cat : Animal
{ /* ... */ }
[edit] D
class Animal {
// ...
}
class Dog: Animal {
// ...
}
class Lab: Dog {
// ...
}
class Collie: Dog {
// ...
}
class Cat: Animal {
// ...
}
void main() {}
[edit] Delphi
type
Animal = class(TObject)
private
// private functions/variables
public
// public functions/variables
end;
Dog = class(Animal);
Cat = class(Animal);
Collie = class(Dog);
Lab = class(Dog);
[edit] DWScript
type
Animal = class(TObject)
private
// private functions/variables
public
// public functions/variables
end;
type Dog = class(Animal) end;
type Cat = class(Animal) end;
type Collie = class(Dog) end;
type Lab = class(Dog) end;
[edit] 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 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 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]
}
Setting up the task's specified tree:
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])
Some example objects:
def fido implements LabStamp {}
def tom implements CatStamp {}
def brick {} # not an animal
Testing against the types:
? 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
[edit] Eiffel
class
ANIMAL
end
class
DOG
inherit
ANIMAL
end
class
CAT
inherit
ANIMAL
end
class
LAB
inherit
DOG
end
class
COLLIE
inherit
DOG
end
[edit] Factor
TUPLE: animal ;
TUPLE: dog < animal ;
TUPLE: cat < animal ;
TUPLE: lab < dog ;
TUPLE: collie < dog ;
[edit] Fancy
class Animal {
# ...
}
class Dog : Animal {
# ...
}
class Cat : Animal {
# ...
}
class Lab : Dog {
# ...
}
class Collie : Dog {
# ...
}
[edit] Fantom
class Animal
{
}
class Dog : Animal
{
}
class Cat : Animal
{
}
class Lab : Dog
{
}
class Collie : Dog
{
}
[edit] Forth
There are numerous, mutually incompatible object oriented frameworks for Forth. This one works with the FOOS preprocessor extension of 4tH.
include 4pp/lib/foos.4pp
:: Animal class end-class {} ;
:: Dog extends Animal end-extends {} ;
:: Cat extends Animal end-extends {} ;
:: Lab extends Dog end-extends {} ;
:: Collie extends Dog end-extends {} ;
[edit] 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).
module anim
type animal
end type animal
type, extends(animal) :: dog
end type dog
type, extends(animal) :: cat
end type cat
type, extends(dog) :: lab
end type lab
type, extends(dog) :: collie
end type collie
end module anim
[edit] F#
The () behind the class names indicates a public default constructor; you need some type of public constructor to derive from a class.
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()
[edit] 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.
package main
type animal struct {
alive bool
}
type dog struct {
animal
obedienceTrained bool
}
type cat struct {
animal
litterBoxTrained bool
}
type lab struct {
dog
color string
}
type collie struct {
dog
catchesFrisbee bool
}
func main() {
var pet lab
pet.alive = true
pet.obedienceTrained = false
pet.color = "yellow"
}
[edit] Groovy
class Animal{
//contents go here...
}
class Dog extends Animal{
//contents go here...
}
class Cat extends Animal{
//contents go here...
}
class Lab extends Dog{
//contents go here...
}
class Collie extends Dog{
//contents go here...
}
[edit] 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
class Animal a => Cat a
class Animal a => Dog a
class Dog a => Lab a
class Dog a => Collie a
[edit] Haxe
class Animal {
// ...
}
class Cat extends Animal {
// ...
}
class Dog extends Animal {
// ...
}
class Lab extends Dog {
// ...
}
class Collie extends Dog {
// ...
}
[edit] Icon and Unicon
This example only works in Unicon.
class Animal ()
end
class Dog : Animal ()
end
class Cat : Animal ()
end
class Lab : Dog ()
end
class Collie : Dog ()
end
[edit] Inform 7
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.
"Animal" is actually a predefined kind in Inform 7, so its definition here is redundant (but legal).
[edit] Io
Animal := Object clone
Cat := Animal clone
Dog := Animal clone
Collie := Dog clone
Lab := Dog clone
[edit] J
Here is how this would normally be done:
coclass 'Animal'
coclass 'Dog'
coinsert 'Animal'
coclass 'Cat'
coinsert 'Animal'
coclass 'Lab'
coinsert 'Dog'
coclass 'Collie'
coinsert 'Dog'
coclass specifies that following definitions will be within the named class, and coinsert 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 classes and objects).
See http://www.jsoftware.com/help/jforc/modular_code.htm
That said, some operations in J -- including coinsert -- will create classes if they did not already exist. So the above may be simplified to:
coinsert_Dog_ 'Animal'
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).
[edit] Java
public class Animal{
//functions go here...
}
public class Dog extends Animal{
//functions go here...
}
public class Cat extends Animal{
//functions go here...
}
public class Lab extends Dog{
//functions go here...
}
public class Collie extends Dog{
//functions go here...
}
[edit] JavaScript
JavaScript is a class-free, object-oriented language, and as such, it uses prototypal inheritance instead of classical inheritance.
function Animal() {
// ...
}
function Dog() {
// ...
}
Dog.prototype = new Animal();
function Cat() {
// ...
}
Cat.prototype = new Animal();
function Collie() {
// ...
}
Collie.prototype = new Dog();
function Lab() {
// ...
}
Lab.prototype = new Dog();
Animal.prototype.speak = function() {print("an animal makes a sound")};
var lab = new Lab();
lab.speak(); // shows "an animal makes a sound"
[edit] Kite
class Animal [
#Method goes here
];
class Dog from Animal [
#Method goes here
];
class Lab from Dog [
#Method goes here
];
class collie from Dog [
#Method goes here
];
[edit] Lisaac
Section Header
+ name := ANIMAL;
// ...
Section Header
+ name := CAT;
Section Inherit
- parent : ANIMAL := ANIMAL;
// ...
Section Header
+ name := DOG;
Section Inherit
- parent : ANIMAL := ANIMAL;
// ...
Section Header
+ name := LAB;
Section Inherit
- parent : DOG := DOG;
// ...
Section Header
+ name := COLLIE;
Section Inherit
- parent : DOG := DOG;
// ...
[edit] 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)).
:- end_object.
:- object(animal,
specializes(thing)).
...
:- end_object.
:- object(dog,
specializes(animal)).
...
:- end_object.
:- object(cat,
specializes(animal)).
...
:- end_object.
:- object(lab,
specializes(dog)).
...
:- end_object.
:- object(collie,
specializes(dog)).
...
:- end_object.
[edit] Objective-C
@interface Animal : NSObject
{
// ...
}
// ...
@end
@interface Dog : Animal
{
// ...
}
// ...
@end
@interface Lab : Dog
{
// ...
}
// ...
@end
@interface Collie : Dog
{
// ...
}
// ...
@end
@interface Cat : Animal
{
// ...
}
// ...
@end
[edit] Objeck
class Animal
{ #~ ... ~# }
class Dog from Animal
{ #~ ... ~# }
class Lab from Dog
{ #~ ... ~# }
class Collie from Dog
{ #~ ... ~# }
class Cat from Animal
{ #~ ... ~# }
[edit] OCaml
class animal =
object (self)
(*functions go here...*)
end
class dog =
object (self)
inherit animal
(*functions go here...*)
end
class cat =
object (self)
inherit animal
(*functions go here...*)
end
class lab =
object (self)
inherit dog
(*functions go here...*)
end
class collie =
object (self)
inherit dog
(*functions go here...*)
end
[edit] ooRexx
-- subclass of object by default
::class animal
::class cat subclass animal
::class dog subclass animal
::class lab subclass dog
::class collie subclass dog
[edit] OxygenBasic
class animal
method show() as string
return "Animal "
end method
end Class
class dog
from Animal Animal
method show() as string
return animal.show()+"dog "
end method
end Class
class cat
from animal animal
method show() as string
return animal.show()+"cat "
end method
end Class
class Lab
from dog dog
method show() as string
return dog.show()+"Lab "
end method
end Class
class Collie
from dog dog
method show() as string
return dog.show()+"Collie "
end method
end Class
Collie c
print c.show 'result: Animal Dog Collie
[edit] Oz
class Animal
%% ...
end
class Dog from Animal
%% ...
end
class Lab from Dog
%% ...
end
class Collie from Dog
%% ...
end
class Cat from Animal
%% ...
end
[edit] Pascal
See Delphi
[edit] Perl
package Animal;
#functions go here...
1;
package Dog;
use Animal;
@ISA = qw( Animal );
#functions go here...
1;
package Cat;
use Animal;
@ISA = qw( Animal );
#functions go here...
1;
package Lab;
use Dog;
@ISA = qw( Dog );
#functions go here...
1;
package Collie;
use Dog;
@ISA = qw( Dog );
#functions go here...
1;
The same using the MooseX::Declare module:
use MooseX::Declare;
class Animal {
# methods go here...
}
class Dog extends Animal {
# methods go here...
}
class Cat extends Animal {
# methods go here...
}
class Lab extends Dog {
# methods go here...
}
class Collie extends Dog {
# methods go here...
}
[edit] Perl 6
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
- Output:
Dog() Animal() Dog() Animal()
The .^parents notation indicates a method call to the object's metaobject rather than to the object itself.
[edit] PHP
class Animal {
// functions go here...
}
class Dog extends Animal {
// functions go here...
}
class Cat extends Animal {
// functions go here...
}
class Lab extends Dog {
// functions go here...
}
class Collie extends Dog {
// functions go here...
}
[edit] PicoLisp
(class +Animal)
(class +Dog +Animal)
(class +Cat +Animal)
(class +Lab +Dog)
(class +Collie +Dog)
: (dep '+Animal)
+Animal
+Cat
+Dog
+Collie
+Lab
[edit] 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.
[edit] Native version
Interface Animal
Eat()
Sleep()
EndInterface
Interface Cat Extends Animal
ChaseMouse()
EndInterface
Interface Dog Extends Animal
Bark()
WagTail()
EndInterface
Interface Lab Extends Dog
Swim()
EndInterface
Interface Collie Extends Dog
HeardSheep()
EndInterface
[edit] Simple OOP Version
Using the open-source precompiler SimpleOOP.
Class Animal
EndClass
Class Dog Extends Animal
Public Method Bark()
EndMethod
EndClass
Class Cat Extends Animal
Public Method Sleep()
EndMethod
EndClass
Class Lab Extends Dog
Public Method Swim()
EndMethod
EndClass
Class Collie Extends Dog
Public Method Fetch()
EndMethod
EndClass
;- test the code
*Lassie.Collie = NewObject.Collie
*Lassie\Bark()
*Lassie\Fetch()
[edit] Python
Unrevised style classes:
class Animal:
pass #functions go here...
class Dog(Animal):
pass #functions go here...
class Cat(Animal):
pass #functions go here...
class Lab(Dog):
pass #functions go here...
class Collie(Dog):
pass #functions go here...
New style classes:
import timeOutput:
class Animal(object):
def __init__(self, birth=None, alive=True):
self.birth = birth if birth else time.time()
self.alive = alive
def age(self):
return time.time() - self.birth
def kill(self):
self.alive = False
class Dog(Animal):
def __init__(self, bones_collected=0, **kwargs):
self.bone_collected = bones_collected
super(Dog, self).__init__(**kwargs)
class Cat(Animal):
max_lives = 9
def __init__(self, lives=max_lives, **kwargs):
self.lives = lives
super(Cat, self).__init__(**kwargs)
def kill(self):
if self.lives>0:
self.lives -= 1
if self.lives == 0:
super(Cat, self).kill()
else:
raise ValueError
return self
class Labrador(Dog):
def __init__(self, guide_dog=False, **kwargs):
self.guide_dog=False
super(Labrador, self).__init__(**kwargs)
class Collie(Dog):
def __init__(self, sheep_dog=False, **kwargs):
self.sheep_dog=False
super(Collie, self).__init__(**kwargs)
lassie = Collie()
felix = Cat()
felix.kill().kill().kill()
mr_winkle = Dog()
buddy = Labrador()
buddy.kill()
print "Felix has",felix.lives, "lives, ","Buddy is %salive!"%("" if buddy.alive else "not ")
Felix has 6 lives, Buddy is not alive!
[edit] R
[edit] S3
Inheritance is implemented by setting the object's class attribute with a character vector.
aCollie <- "woof"
class(aCollie) <- c("Collie", "Dog", "Animal")
[edit] S4
Inheritance is implemented by using the 'contains' argument in setClass
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")
[edit] Racket
#lang racket
(define animal% (class object% (super-new)))
(define dog% (class animal% (super-new)))
(define cat% (class animal% (super-new)))
(define lab% (class dog% (super-new)))
(define collie% (class dog% (super-new)))
;; unit tests
(require rackunit)
(check-true (is-a? (new dog%) animal%))
(check-false (is-a? (new collie%) cat%))
[edit] REBOL
rebol [
Title: "Inheritance"
Author: oofoe
Date: 2009-12-08
URL: http://rosettacode.org/wiki/Inheritance
]
; REBOL provides subclassing through its prototype mechanism:
Animal: make object! [
legs: 4
]
Dog: make Animal [
says: "Woof!"
]
Cat: make Animal [
says: "Meow..."
]
Lab: make Dog []
Collie: make Dog []
; Demonstrate inherited properties:
print ["Cat has" Cat/legs "legs."]
print ["Lab says:" Lab/says]
Output:
Cat has 4 legs. Lab says: Woof!
[edit] Ruby
inherited is a method defined on an instance of a Class object. It is invoked when a new subclass of the current class is defined (i.e. at the end statement of a class definition).
class Animal
#functions go here...
def self.inherited(subclass)
puts "new subclass of #{self}: #{subclass}"
end
end
class Dog < Animal
#functions go here...
end
class Cat < Animal
#functions go here...
end
class Lab < Dog
#functions go here...
end
class Collie < Dog
#functions go here...
end
Output
new subclass of Animal: Dog new subclass of Dog: Lab new subclass of Dog: Collie new subclass of Animal: Cat
[edit] Scala
Scala has both classes and traits. Classes can only be singly inherited, but both
can inherit a trait multiple times. This inheritance can be declared at the point
of instantiation as well, precluding the need to declare a trait or class for the
sole purpose of combining traits. For the simple inheritance chain of this task,
any (or all) of the class keywords below can be replaced with trait
class Animal
class Dog extends Animal
class Cat extends Animal
class Lab extends Dog
class Collie extends Dog
[edit] Seed7
Seed7 object orientation is based on interface types and implementation types. The example below defines a hierarchy of implementation types.
$ include "seed7_05.s7i";
const type: Animal is new struct
# ...
end struct;
const type: Dog is sub Animal struct
# ...
end struct;
const type: Lab is sub Dog struct
# ...
end struct;
const type: Collie is sub Dog struct
# ...
end struct;
const type: Cat is sub Animal struct
# ...
end struct;
[edit] Slate
define: #Animal &parents: {Cloneable}.
define: #Dog &parents: {Animal}.
define: #Cat &parents: {Animal}.
define: #Lab &parents: {Dog}.
define: #Collie &parents: {Dog}.
[edit] 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.
Object subclass: #Animal
instanceVariableNames: ' ' "* space separated list of names *"
classVariableNames: ' '
poolDictionaries: ' '
category: ' ' !
"* declare methods here, separated with '!' *"
"* !Animal methodsFor: 'a category'! *"
"* methodName *"
"* method body! !
!Animal subclass: #Dog
"* etc. *" !
!Animal subclass: #Cat
"* etc. *" !
!Dog subclass: #Lab
"* etc. *" !
!Dog subclass: #Collie
"* etc. *" !
[edit] Tcl
orpackage require TclOO
oo::class create Animal {
# ...
}
oo::class create Dog {
superclass Animal
# ...
}
oo::class create Cat {
superclass Animal
# ...
}
oo::class create Collie {
superclass Dog
# ...
}
oo::class create Lab {
superclass Dog
# ...
}
[edit] TXR
For exception symbols only.
@(defex cat animal)
@(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.
If we throw an exception of type lab, it can be caught in a catch for a dog or for an animal. Continuing with the query:
@(try)
@ (throw lab "x")
@(catch animal (arg))
@(end)
Test:
$ txr dog-cat.txr arg="x"
[edit] Vorpal
pet = new()
cat = new(pet)
dog = new(pet)
fido = new(dog)
felix = new(cat)
[edit] Visual Basic .NET
Class Animal
' ...
End Class
Class Dog
Inherits Animal
' ...
End Class
Class Lab
Inherits Dog
' ...
End Class
Class Collie
Inherits Dog
' ...
End Class
Class Cat
Inherits Animal
' ...
End Class
- Programming Tasks
- Basic language learning
- Object oriented
- Type System
- Encyclopedia
- ActionScript
- Modula-2/Omit
- Ada
- Aikido
- AutoHotkey
- BBC BASIC
- C
- C++
- Clojure
- Common Lisp
- Component Pascal
- C sharp
- D
- Delphi
- DWScript
- E
- Eiffel
- Factor
- Fancy
- Fantom
- Forth
- Fortran
- F Sharp
- Go
- Groovy
- Haskell
- Haxe
- Unicon
- Inform 7
- Io
- J
- Java
- JavaScript
- Kite
- Lisaac
- Logtalk
- Objective-C
- Objeck
- OCaml
- OoRexx
- OxygenBasic
- Oz
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- PureBasic
- Python
- R
- Racket
- REBOL
- Ruby
- Scala
- Seed7
- Slate
- Smalltalk
- Tcl
- TclOO
- TXR
- Vorpal
- ALGOL 68/Omit
- Batch File/Omit
- AWK/Omit
- M4/Omit
- Metafont/Omit
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit
- MIPS Assembly/Omit
- PARI/GP/Omit
- Visual Basic .NET
- ML/I/Omit
- Mathematica/Omit
- Maxima/Omit