Classes: Difference between revisions

25,696 bytes added ,  5 months ago
m
→‎{{header|Wren}}: Changed to Wren S/H
No edit summary
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(35 intermediate revisions by 19 users not shown)
Line 1:
[[Category:Object oriented]]
{{task|Basic language learning}}
[[Category:Object oriented]]
[[Category:Type System]]
[[Category:Encyclopedia]]
{{task|Basic language learning}}
 
In [[object-oriented programming]] '''class''' is a set (a [[wp:Transitive_closure|transitive closure]]) of types bound by the relation of [[inheritance]]. It is said that all types derived from some base type T and the type T itself form a class T.
Line 37 ⟶ 38:
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
<br><br>
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">T MyType
Int public_variable // member variable = instance variable
. Int private_variable
Line 48:
F someMethod() // member function = method
.private_variable = 1
.public_variable = 10</langsyntaxhighlight>
 
Note that member functions in 11l by default are not polymorphic; if you want a polymorphic member function, you have to mark it as virtual. Example:
<langsyntaxhighlight lang="11l">T MyType
F.virtual.new someMethod() -> N // this is polymorphic
print()</langsyntaxhighlight>
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">package {
public class MyClass {
Line 76 ⟶ 75:
}
}
}</langsyntaxhighlight>
 
=={{header|Ada}}==
Class is used in many languages to provide both encapsulation, or grouping of data and actions, and type definition. Ada packages provide encapsulation or grouping while type definitions are done using the ''type'' reserved word. Types participating in inheritance are named ''tagged'' record types.
 
A package specification has the following form:
<langsyntaxhighlight lang="ada">package My_Package is
type My_Type is tagged private;
procedure Some_Procedure(Item : out My_Type);
Line 90 ⟶ 88:
Variable : Integer := -12;
end record;
end My_Package;</langsyntaxhighlight>
The type declaration at the top of the package gives public visibility to the private tagged type My_Type. Since My_Type is declared to be private, the public has no visibility of its structure. The type must be treated as a black box. The private section of the package specification includes the actual tagged record definition. Note that the data member Variable is initialized to -12. This corresponds to a default constructor for the type.
 
The package body must contain the implementation of the procedures and functions declared in the package specification.
<langsyntaxhighlight lang="ada"> package body My_Package is
procedure Some_Procedure(Item : out My_Type) is
begin
Line 106 ⟶ 104:
return Temp;
end Set;
end My_Package;</langsyntaxhighlight>
The Set function acts as a conversion constructor for My_Type.
 
An instance is typically created outside the package:
<langsyntaxhighlight lang="ada">with My_Package; use My_Package;
 
procedure Main is
Line 117 ⟶ 115:
Some_Procedure(Foo); -- Foo is doubled
Foo := Set(2007); -- Foo.Variable is set to 2007
end Main;</langsyntaxhighlight>
 
=={{header|Aikido}}==
Aikido provides classes with single inheritance and multiple interface implementation. A class takes a set of constructor arguments and provides a set of public functions, operators, classes, monitors and threads.
<langsyntaxhighlight lang="aikido">class Circle (radius, x, y) extends Shape (x, y) implements Drawable {
var myvec = new Vector (x, y)
 
Line 127 ⟶ 124:
// draw the circle
}
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{trans|python}}
Line 141 ⟶ 137:
Other examples of this experimental approach are located at pages: [[Life in two dimensions#ALGOL 68|Life in two dimensions]], [[Playing Cards#ALGOL 68|Playing Cards]] and [[Stack#ALGOL 68|Stack]].
 
<langsyntaxhighlight lang="algol68">MODE MYDATA = STRUCT(
INT name1
);
Line 222 ⟶ 218:
print (((name OF person2), ": ",
(gender OF person2|(STRING gender):gender|attribute error), " "));
print (((age OF person2|(INT age):age|attribute error), new line)) # "Jane Female 23" #</langsyntaxhighlight>
{{out}}
<pre>
Line 228 ⟶ 224:
Jane: Female +23
</pre>
 
=={{header|AmigaE}}==
<langsyntaxhighlight lang="amigae">OBJECT a_class
varA, varP
ENDOBJECT
Line 256 ⟶ 251:
WriteF('\d\n', obj.getP())
END obj
ENDPROC</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="arturo">//; Let'sdefining definea ourcustom classtype
define :person [ ; define a new custom type "Person"
name ; with fields: name, surname, age
surname
age
][
; with custom post-construction initializer
init: [
this\name: capitalize this\name
]
 
; custom print function
Person #{
print: [
// first the class variables
render "NAME: |this\name|, SURNAME: |this\surname|, AGE: |this\age|"
name ""
]
surname ""
age 0
 
; custom comparison operator
// then the constructor (optional)
compare: 'age
init [n,s,a]{
]
name n
surname s
age a
}
 
//; thencreate anothera method (optionalfor again,our ofc)custom type
sayHello: {function [this][
ensure -> is? :person this
print "Hello " + name + "!"
}
}
 
print ["Hello" this\name]
// Let's create a new Person object
]
person $(new ~Person "John" "Doe" 33)
 
; create new objects of our custom type
// Let's invoke an object method
a: to :person ["John" "Doe" 34] ; let's create 2 "Person"s
person.sayHello
b: to :person ["jane" "Doe" 33] ; and another one
 
; call pseudo-inner method
// Let's access some object variable
sayHello a ; Hello John
print "the person's age is: " + person.age
sayHello b ; Hello Jane
 
; access object fields
// Let's change some of the object's properties
print ["The first person's name is:" a\name] ; The first person's name is: John
person.surname "boom"
print ["The second person's name is:" b\name] ; The second person's name is: Jane
 
//; And let's print ourchanging object againfields
a\name: "Bob"
// to see what we've done
sayHello a ; Hello Bob
log person</lang>
 
; verifying object type
{{out}}
print type a ; :person
print is? :person a ; true
 
; printing objects
print a ; NAME: John, SURNAME: Doe, AGE: 34
 
; sorting user objects (using custom comparator)
<pre>Hello John!
sort @[a b] ; Jane..., John...
the person's age is: 33
sort.descending @[a b] ; John..., Jane... </syntaxhighlight>
#{
 
age 33
{{out}}
init <function: 0x1015A8D40>
 
name "John"
<pre>Hello John
sayHello <function: 0x1015A8DA0>
Hello Jane
surname "boom"
The first person's name is: John
}</pre>
The second person's name is: Jane
Hello Bob
:person
true
NAME: Bob, SURNAME: Doe, AGE: 34</pre>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
AutoHotkey_L is prototype-based. However, for convenience, class-syntax may be used to create a base object.
<langsyntaxhighlight AutoHotkeylang="autohotkey">obj := new MyClass
obj.WhenCreated()
 
Line 330 ⟶ 340:
MsgBox, % "Object created at " this.time " on " this.date
}
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
==={{header|BaCon}}===
{{works with|QuickBasic|4.5}}
This is an '''advanced feature''' to extend the the compiler we can also compile using g++ or clang++ using PRAGMA
<lang basic> DECLARE SUB MyClassDelete (pthis AS MyClass)
DECLARE SUB MyClassSomeMethod (pthis AS MyClass)
DECLARE SUB MyClassInit (pthis AS MyClass)
 
<syntaxhighlight lang="cpp">
TYPE MyClass
PRAGMA COMPILER g++
Variable AS INTEGER
PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive
END TYPE
 
OPTION PARSE FALSE
DIM obj AS MyClass
MyClassInit obj
MyClassSomeMethod obj
 
SUB MyClassInit (pthis AS MyClass)
pthis.Variable = 0
END SUB
 
'---The class does the declaring for you
SUB MyClassSomeMethod (pthis AS MyClass)
pthis.Variable = 1
END SUB</lang>
 
CLASS Books
=={{header|BBC BASIC}}==
public:
const char* title;
const char* author;
const char* subject;
int book_id;
END CLASS
 
 
'---pointer to an object declaration (we use a class called Books)
DECLARE Book1 TYPE Books
'--- the correct syntax for class
Book1 = Books()
 
 
'--- initialize the strings const char* in c++
Book1.title = "C++ Programming to bacon "
Book1.author = "anyone"
Book1.subject ="RECORD Tutorial"
Book1.book_id = 1234567
 
 
PRINT "Book title : " ,Book1.title FORMAT "%s%s\n"
PRINT "Book author : ", Book1.author FORMAT "%s%s\n"
PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n"
PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"
</syntaxhighlight>
 
 
Now the same but using the c++ "new" command and arrow operators syntax
 
<syntaxhighlight lang="cpp">
PRAGMA COMPILER g++
PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive
 
OPTION PARSE FALSE
 
 
'---The class does the declaring for you
 
CLASS Books
public:
const char* title;
const char* author;
const char* subject;
int book_id;
END CLASS
 
 
'---pointer to an object declaration (we use a class called Books)
DECLARE Book1 TYPE Books*
'--- the correct syntax for class
Book1 = new Books()
 
 
'--- initialize the strings const char* in c++
Book1->title = "C++ Programming to bacon "
Book1->author = "anyone"
Book1->subject ="RECORD Tutorial"
Book1->book_id = 1234567
 
 
PRINT "Book title : " ,Book1->title FORMAT "%s%s\n"
PRINT "Book author : ", Book1->author FORMAT "%s%s\n"
PRINT "Book subject : ", Book1->subject FORMAT "%s%s\n"
PRINT "Book book_id : ", Book1->book_id FORMAT "%s%d\n"
</syntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"CLASSLIB"
REM Declare the class:
Line 373 ⟶ 441:
REM Discard the instance:
PROC_discard(myclass{})</langsyntaxhighlight>
 
==={{header|QuickBASIC}}===
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="basic"> TYPE MyClass
Variable AS INTEGER
END TYPE
 
DECLARE SUB MyClassDelete (pthis AS MyClass)
DECLARE SUB MyClassSomeMethod (pthis AS MyClass)
DECLARE SUB MyClassInit (pthis AS MyClass)
 
DIM obj AS MyClass
MyClassInit obj
MyClassSomeMethod obj
 
SUB MyClassInit (pthis AS MyClass)
pthis.Variable = 0
END SUB
 
SUB MyClassSomeMethod (pthis AS MyClass)
pthis.Variable = 1
END SUB</syntaxhighlight>
 
=={{header|blz}}==
<langsyntaxhighlight lang="blz">
# Constructors can take parameters (that automatically become properties)
constructor Ball(color, radius)
Line 393 ⟶ 483:
print(red_ball)
# => a red ball with radius 2
</syntaxhighlight>
</lang>
=={{header|BQN}}==
 
Classes with a constructor can be defined in BQN with the help of a namespace. All data members are immutable(private) and can only be modified with the help of exported functions. Exported variables can be accessed, but they cannot be mutated(this may change in the future).
 
<syntaxhighlight lang="bqn">ExClass ← {
𝕊 value: # Constructor portion
priv ← value
priv2 ⇐ 0
ChangePriv ⇐ { priv ↩ 𝕩 }
DispPriv ⇐ {𝕊: •Show priv‿priv2 }
}
 
obj ← ExClass 5
obj.DispPriv@
obj.ChangePriv 6
obj.DispPriv@</syntaxhighlight>
=={{header|Bracmat}}==
Bracmat has no class-inheritance. Any object can function as a template for creating other objects.
<langsyntaxhighlight lang="bracmat">( ( resolution
= (x=)
(y=)
Line 404 ⟶ 510:
& new$(resolution,640,480):?VGA
& new$(resolution,1920,1080):?1080p
& out$("VGA: horizontal " !(VGA..x) " vertical " !(VGA..y)));</langsyntaxhighlight>
{{out}}
<pre>VGA: horizontal 640 vertical 480</pre>
 
=={{header|C}}==
{{works with|gcc|4.0.2}}
<syntaxhighlight lang="c">
<lang c>
#include <stdlib.h>
 
Line 441 ⟶ 546:
MyClass obj = MyClass_new();
MyClass_someMethod(obj);
MyClass_delete(&obj);</langsyntaxhighlight>
=={{header|C sharp|C#}}==
 
<syntaxhighlight lang="csharp">public class MyClass
{
public MyClass()
{
}
public void SomeMethod()
{
}
private int _variable;
public int Variable
{
get { return _variable; }
set { _variable = value; }
}
public static void Main()
{
// instantiate it
MyClass instance = new MyClass();
// invoke the method
instance.SomeMethod();
// set the variable
instance.Variable = 99;
// get the variable
System.Console.WriteLine( "Variable=" + instance.Variable.ToString() );
}
}</syntaxhighlight>
=={{header|C++}}==
{{works with|g++|4.0.2}}
<langsyntaxhighlight lang="cpp">class MyClass
{
public:
Line 473 ⟶ 604:
MyClass* pInstance = new MyClass;
// Instances allocated with new must be explicitly destroyed when not needed any more:
delete pInstance;</langsyntaxhighlight>
 
Note: <tt>MyClass instance();</tt> would ''not'' define an instance, but declare a function returning an instance. Accidentally declaring functions when object definitions are wanted is a rather common bug in C++.
Line 479 ⟶ 610:
Functions can also be defined inline:
 
<langsyntaxhighlight lang="cpp">class MyClass
{
public:
Line 486 ⟶ 617:
private:
int variable;
};</langsyntaxhighlight>
 
Note that member functions in C++ by default are ''not'' polymorphic; if you want a polymorphic member function, you have to mark it as virtual. In that case, you should also add a virtual destructor, even if that is empty. Example:
 
<langsyntaxhighlight lang="cpp">class MyClass
{
public:
virtual void someMethod(); // this is polymorphic
virtual ~MyClass(); // destructor
};</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<lang csharp>public class MyClass
{
public MyClass()
{
}
public void SomeMethod()
{
}
private int _variable;
public int Variable
{
get { return _variable; }
set { _variable = value; }
}
public static void Main()
{
// instantiate it
MyClass instance = new MyClass();
// invoke the method
instance.SomeMethod();
// set the variable
instance.Variable = 99;
// get the variable
System.Console.WriteLine( "Variable=" + instance.Variable.ToString() );
}
}</lang>
 
=={{header|Clojure}}==
Clojure gives you several options, and to help you decide which is more appropriate to use, see the [https://github.com/cemerick/clojure-type-selection-flowchart/ Clojure type selection flowchart].
 
defrecord example:
<langsyntaxhighlight lang="clojure">
; You can think of this as an interface
(defprotocol Foo (getFoo [this]))
Line 538 ⟶ 640:
; Create instance and invoke our method to return field value
(-> (Example1. "Hi") .getFoo)
"Hi"</langsyntaxhighlight>
 
=={{header|COBOL}}==
<!-- This took far too long to create and to get to compile. -->
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
CLASS-ID. my-class INHERITS base.
Line 607 ⟶ 708:
.
END PROGRAM example-class-use.</langsyntaxhighlight>
 
=={{header|Coco}}==
<langsyntaxhighlight lang="coco">class Rectangle
# The constructor is defined as a bare function. This
# constructor accepts one argument and automatically assigns it
Line 624 ⟶ 724:
# Instantiate the class using the 'new' operator.
rect = new Rectangle 2</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript"># Create a basic class
class Rectangle
# Constructor that accepts one argument
Line 640 ⟶ 739:
 
# Instantiate the class using the new operator
rect = new Rectangle 2</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defclass circle ()
((radius :initarg :radius
:initform 1.0
Line 654 ⟶ 752:
> (defvar *c* (make-instance 'circle :radius 2))
> (area *c*)
12.566370614359172d0</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
 
Module that defines a Class
<langsyntaxhighlight lang="oberon2">
MODULE Point;
IMPORT
Line 702 ⟶ 799:
END ToString;
END Point.
</syntaxhighlight>
</lang>
Module that uses previous class
<langsyntaxhighlight lang="oberon2">
MODULE DrivePoint;
IMPORT
Line 722 ⟶ 819:
 
END DrivePoint.
</syntaxhighlight>
</lang>
Execute: ^Q DrivePoint.Do<br/>
{{out}}
Line 730 ⟶ 827:
p.y:> 2
</pre>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="crystal">class MyClass
def initialize
Line 746 ⟶ 842:
my_class = MyClass.new
</syntaxhighlight>
</lang>
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio;
 
class MyClass {
Line 790 ⟶ 886:
// prints 'variable = 99'
writeln("variable = ", obj.variable);
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program SampleClass;
 
{$APPTYPE CONSOLE}
Line 836 ⟶ 931:
lMyClass.Free;
end;
end.</langsyntaxhighlight>
 
=={{header|DM}}==
In DM, all "classes" are part of the "object tree". Instance variables, procs (functions), ... are all defined inside this "tree".
Adding elements (procs, variables, classes) to this tree is done by defining the name and such.
 
<syntaxhighlight lang DM="dm">s</langsyntaxhighlight>
 
This declares a type "/s" at the root of the tree, which can now be instantiated.
Line 848 ⟶ 942:
A more complicated example:
 
<syntaxhighlight lang="dm">
<lang DM>
// Declare the class "/foo"
foo
Line 871 ⟶ 965:
x.bar = 10 // Assign to the instance variable.
x.baz() // Call "baz" on our instance.
</syntaxhighlight>
</lang>
 
This is enough to declare a
 
This is enough to declare a
=={{header|Dragon}}==
<langsyntaxhighlight lang="dragon">class run{
func val(){
showln 10+20
}
}
</syntaxhighlight>
</lang>
 
=={{header|DWScript}}==
Methods can be implemented inline or out-of-line, this sample illustrates both.
<syntaxhighlight lang="delphi">type
<lang Delphi>type
TMyClass = class
private
Line 909 ⟶ 1,001:
 
lMyClass.SomeField := 99;
lMyClass.SomeMethod;</langsyntaxhighlight>
 
=={{header|E}}==
In E, classes, constructors, and instance variables are not built into the language. This is an example of the basic convention; different cases may call for objects built in different ways.
 
<langsyntaxhighlight lang="e">def makeColor(name :String) {
def color {
to colorize(thing :String) {
Line 921 ⟶ 1,012:
}
return color
}</langsyntaxhighlight>
 
Example interactive session creating and using it:
 
<langsyntaxhighlight lang="e">? def red := makeColor("red")
# value: <color>
 
? red.colorize("apple")
# value: "red apple"</langsyntaxhighlight>
=={{header|EchoLisp}}==
<syntaxhighlight lang="lisp">
(lib 'gloops) ; load oo library
 
(define-class Person null (name (age :initform 66)))
(define-method tostring (Person) (lambda (p) ( format "🚶 %a " p.name)))
(define-method mailto (Person Person) (lambda( p o) (printf "From %a to️ %a : ..." p o)))
 
;; define a sub-class of Person with same methods
(define-class Writer (Person) (books))
(define-method tostring (Writer) (lambda (w)( format "🎩 %a" w.name)))
(define-method mailto (Person Writer)
(lambda (p w) (printf " From %a (age %d). Dear writer of %a ..." p p.age w.books )))
 
</syntaxhighlight>
{{Output}}
<syntaxhighlight lang="lisp">
;; instantiate
(define simone (make-instance Person :name 'simone :age 42)) ;; slots values by name
(define antoinette (make-instance Person :name 'antoinette :age 37))
(define albert (Person "albert" 33)) ;; quick way : slots values in order
(define simon (make-instance Writer :name "simon" :books '(my-life my-bike)))
 
 
(mailto simone simon) ;; method Person-Writer
(mailto simone antoinette) ;; method Person-Person
(mailto simon albert) ;; no method Writer-Person : call 'super' Person-Person
(mailto simon simon) ;; no mehod Writer-Writer : call 'super' Person-Writer
From 🚶 simone (age 42). Dear writer of (my-life my-bike) ...
From 🚶 simone to️ 🚶 antoinette : ...
From 🎩 simon to️ 🚶 albert : ...
From 🎩 simon (age 66). Dear writer of (my-life my-bike) ...
</syntaxhighlight>
=={{header|Eiffel}}==
=== The Most Basic Form of Class ===
The shortest way to write an Eiffel class is to have the class keyword, followed by the name of the class (all caps), and ending with the end keyword.
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class MY_CLASS
end
</syntaxhighlight>
</lang>
 
=== Add a Creation Procedure (Constructor) ===
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class MY_CLASS
 
Line 955 ⟶ 1,079:
 
end
</syntaxhighlight>
</lang>
=== Add Multiple Creation Procedures (Constructors) ===
In Eiffel, you may have more than one creation procedure (or "Constructor").
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class MY_CLASS
 
Line 1,002 ⟶ 1,126:
 
end
</syntaxhighlight>
</lang>
 
=== Add some Properties & Methods ===
Below, we've added three attributes (i.e. "Properties"). The "make" is not only a "Constructor" (Creation Procedure), but also an example of a "Method".
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class MY_CLASS
 
Line 1,055 ⟶ 1,179:
 
end
</syntaxhighlight>
</lang>
 
=={{header|EchoLisp}}==
<lang lisp>
(lib 'gloops) ; load oo library
 
(define-class Person null (name (age :initform 66)))
(define-method tostring (Person) (lambda (p) ( format "🚶 %a " p.name)))
(define-method mailto (Person Person) (lambda( p o) (printf "From %a to️ %a : ..." p o)))
 
;; define a sub-class of Person with same methods
(define-class Writer (Person) (books))
(define-method tostring (Writer) (lambda (w)( format "🎩 %a" w.name)))
(define-method mailto (Person Writer)
(lambda (p w) (printf " From %a (age %d). Dear writer of %a ..." p p.age w.books )))
 
</lang>
{{Output}}
<lang lisp>
;; instantiate
(define simone (make-instance Person :name 'simone :age 42)) ;; slots values by name
(define antoinette (make-instance Person :name 'antoinette :age 37))
(define albert (Person "albert" 33)) ;; quick way : slots values in order
(define simon (make-instance Writer :name "simon" :books '(my-life my-bike)))
 
 
(mailto simone simon) ;; method Person-Writer
(mailto simone antoinette) ;; method Person-Person
(mailto simon albert) ;; no method Writer-Person : call 'super' Person-Person
(mailto simon simon) ;; no mehod Writer-Writer : call 'super' Person-Writer
From 🚶 simone (age 42). Dear writer of (my-life my-bike) ...
From 🚶 simone to️ 🚶 antoinette : ...
From 🎩 simon to️ 🚶 albert : ...
From 🎩 simon (age 66). Dear writer of (my-life my-bike) ...
</lang>
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
class MyClass
{
prop int Variable : prop;
someMethod()
Line 1,120 ⟶ 1,208:
// get the variable
console.printLine("Variable=",instance.Variable)
}</langsyntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
type Bear ^| the type system is informed about the new type,
| here we are in the static context
|^
model # instance context
text name # instance variable
^|
| in EMal the instance variables are ordered, and a default
| variadic constructor is provided by the runtime.
| Every value passed to the constructor sets the instance variable
| according to the order.
|^
fun makeNoise = void by block # method of Bear
writeLine("Growl!")
end
end
type Cat
model
text noise
new by text noise # an explicit constructor
me.noise = noise # we must use me to access instance variables
end
fun makeNoise = void by block
writeLine(me.noise)
end
end
type Main
Bear bear = Bear("Bruno") # creating a new instance
writeLine("The bear is called " + bear.name)
bear.makeNoise()
Cat("Meow").makeNoise()
</syntaxhighlight>
{{out}}
<pre>
The bear is called Bruno
Growl!
Meow
</pre>
 
=={{header|ERRE}}==
ERRE isn't OOP-oriented, but with new PC version 3.0 is possibile to define classes and instance variables, like in this example:
<langsyntaxhighlight ERRElang="erre">PROGRAM CLASS2_DEMO
 
CLASS QUADRATO
Line 1,154 ⟶ 1,282:
PRINT(PERIMETROQ)
END PROGRAM
</syntaxhighlight>
</lang>
The answers is
100
80
 
=={{header|F_Sharp|F#}}==
A minimal example as required by the task description:
<langsyntaxhighlight lang="fsharp">type MyClass(init) = // constructor with one argument: init
let mutable var = init // a private instance variable
member x.Method() = // a simple method
Line 1,169 ⟶ 1,296:
// create an instance and use it
let myObject = new MyClass(42)
myObject.Method()</langsyntaxhighlight>
 
A somewhat more meaningful example, inspired by the Haskell version:
<langsyntaxhighlight lang="fsharp">open System
 
type Shape =
Line 1,186 ⟶ 1,313:
interface Shape with
member x.Perimeter() = 2.0 * width + 2.0 * height
member x.Area() = width * height</langsyntaxhighlight>
=={{header|Factor}}==
 
<syntaxhighlight lang="factor">TUPLE: my-class foo bar baz ;
M: my-class quux foo>> 20 + ;
C: <my-class> my-class
10 20 30 <my-class> quux ! result: 30
TUPLE: my-child-class < my-class quxx ;
C: <my-child-class> my-child-class
M: my-child-class foobar 20 >>quux ;
20 20 30 <my-child-class> foobar quux ! result: 30</syntaxhighlight>
=={{header|Falcon}}==
Falcon classes are a mix of data and code that can be used to instantiate objects. Classes are defined below. Note: inh1...inhN can also be passed the param_list.
<langsyntaxhighlight lang="falcon">class class_name[ ( param_list ) ] [ from inh1[, inh2, ..., inhN] ]
[ static block ]
[ properties declaration ]
[init block]
[method list]
end</langsyntaxhighlight>
Example of a class:
<langsyntaxhighlight lang="falcon">class mailbox( max_msg )
capacity = max_msg * 10
Line 1,211 ⟶ 1,346:
end
end</langsyntaxhighlight>
 
Instantiation:
<langsyntaxhighlight lang="falcon">m = mailbox( 10 )
// Ouputs: Box now ready for 100 messages.</langsyntaxhighlight>
 
=={{header|Factor}}==
<lang factor>TUPLE: my-class foo bar baz ;
M: my-class quux foo>> 20 + ;
C: <my-class> my-class
10 20 30 <my-class> quux ! result: 30
TUPLE: my-child-class < my-class quxx ;
C: <my-child-class> my-child-class
M: my-child-class foobar 20 >>quux ;
20 20 30 <my-child-class> foobar quux ! result: 30</lang>
 
=={{header|Fancy}}==
<langsyntaxhighlight lang="fancy">class MyClass {
read_slot: 'instance_var # creates getter method for @instance_var
@@class_var = []
Line 1,253 ⟶ 1,377:
}
 
myclass = MyClass new</langsyntaxhighlight>
 
=={{header|Fantom}}==
<langsyntaxhighlight Fantomlang="fantom">class MyClass
{
// an instance variable
Line 1,282 ⟶ 1,405:
c := MyClass { x = 3 } // instantiates the class, sets x to 3
}
}</langsyntaxhighlight>
 
=={{header|Forth}}==
{{works with|Win32Forth}}
Line 1,290 ⟶ 1,412:
Declare a class
 
<langsyntaxhighlight lang="forth">:class MyClass <super Object
 
int memvar
Line 1,303 ⟶ 1,425:
:m show: ( -- ) ." Memvar = " memvar . ;m
 
;class</langsyntaxhighlight>
 
Allocate a static object
<syntaxhighlight lang ="forth">MyClass newInstance</langsyntaxhighlight>
 
Allocate a dynamic object, saving its pointer in a global variable.
<syntaxhighlight lang ="forth">New> MyClass value newInstance</langsyntaxhighlight>
 
Call member functions
<langsyntaxhighlight lang="forth">10 set: newInstance
show: newInstance</langsyntaxhighlight>
 
Free a dynamically allocated object
 
<langsyntaxhighlight lang="forth">newInstance dispose
0 to newInstance \ no dangling pointers!</langsyntaxhighlight>
 
Example of dynamic allocation and local variable use"
 
<langsyntaxhighlight lang="forth">: test { \ obj -- }
New> MyClass to obj
show: obj
1000 set: obj
obj dispose ;</langsyntaxhighlight>
 
 
Line 1,333 ⟶ 1,455:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<langsyntaxhighlight lang="forth">include FMS-SI.f
 
:class foo \ begin class foo definition
Line 1,364 ⟶ 1,486:
bar \ 10 30
bar' \ 10 30
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
Creating abstract derived type (abstract class), extended derived types, using constructor and finalization, pointers etc. Works with gfortran 5.0 and intel ifort 15.0.2
 
<langsyntaxhighlight lang="fortran">
!-----------------------------------------------------------------------
!Module accuracy defines precision and some constants
Line 1,549 ⟶ 1,670:
end program rosetta_class
 
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type MyClass
Line 1,578 ⟶ 1,698:
Print mc.MyInt, mc.Treble()
Print "Press any key to quit the program"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,584 ⟶ 1,704:
24 72
</pre>
 
=={{header|GLSL}}==
There are no classes in GLSL, but they can be simulated using structs:
<langsyntaxhighlight lang="glsl">
struct Rectangle{
float width;
Line 1,607 ⟶ 1,726:
return (self.width+self.height)*2.0;
}
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
The task describes several concepts concerning class methods before giving some task requirements. The following code satisfies the task requirements. The concepts described however, are more involved. A discussion of these concepts follows.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,660 ⟶ 1,778:
fmt.Println(forTwo)
fmt.Println(forToo)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,683 ⟶ 1,801:
 
This happens when a method is called through an interface. Consider this code in addition to the example above.
<langsyntaxhighlight lang="go">import reflect
 
type happinessTester interface {
Line 1,708 ⟶ 1,826:
ps.happy())
}
}</langsyntaxhighlight>
On the last line, in the call to ps.happy(), ps is of the interface type happinessTester. The method actually called is based on the underlying concrete type.
For the method call, this is called the receiver type and the variable b (in both happy methods) is called the receiver. Dispatch is based on this single receiver so Go is a single dispatch kind of language.
Line 1,726 ⟶ 1,844:
 
To the extent that an interface represents a class, it is distinct from a type that satisfies it. Interface is one kind of type, but an object of any type can satisfy an interface. The two types&mdash;the interface type and the type satisfying the interface&mdash;are distinct.
 
=={{header|Groovy}}==
A class:
<langsyntaxhighlight lang="groovy">/** Ye olde classe declaration */
class Stuff {
/** Heare bee anne instance variable declared */
def guts
/** This constuctorconstructor converts bits into Stuff */
Stuff(injectedGuts) {
guts = injectedGuts
Line 1,743 ⟶ 1,860:
println "This stuff is flangulating its guts: ${guts}"
}
}</langsyntaxhighlight>
 
A demonstration:
<langsyntaxhighlight lang="groovy">def stuff = new Stuff('''
I have made mistakes in the past.
I have made mistakes in the future.
Line 1,761 ⟶ 1,878:
'''
 
stuff.flangulate()</langsyntaxhighlight>
 
{{out}}
Line 1,774 ⟶ 1,891:
and neither do we.
-- President George W. Bush</pre>
 
=={{header|Haskell}}==
Haskell is entirely statically typed; that is, the type of every expression is completely determined at compile-time.
Hence, the usual approach to object-oriented programming, in which the actual method invoked by a method call isn't determined until runtime (think of C++'s virtual functions), is impossible in Haskell 98.
Haskell's type classes allow for polymorphic functions, but all the polymorphism happens at compile-time (think of C++ templates) without the use of language extensions (existential types).
<langsyntaxhighlight lang="haskell">class Shape a where
perimeter :: a -> Double
area :: a -> Double
Line 1,811 ⟶ 1,927:
{- The correct version of apRatio (and hence the correct
implementations of perimeter and area) is chosen based on the type
of the argument. -}</langsyntaxhighlight>
 
The primary way to simulate run-time polymorphism in Haskell is to use a single algebraic data type with multiple constructors, rather than several types belonging to a single class.
 
<langsyntaxhighlight lang="haskell">data Shape = Rectangle Double Double | Circle Double
{- This Shape is a type rather than a type class. Rectangle and
Circle are its constructors. -}
Line 1,837 ⟶ 1,953:
{- The value returned by apRatio is determined by the return values
of area and perimeter, which just happen to be defined differently
for Rectangles and Circles. -}</langsyntaxhighlight>
 
== Icon and {{header|Unicon}} ==
Unicon supports classes.
<langsyntaxhighlight Uniconlang="unicon">class Example (x) # 'x' is a field in class
 
# method definition
Line 1,861 ⟶ 1,977:
write (x2.x)
write (x2.double ()) # call a method
end</langsyntaxhighlight>
 
=={{header|J}}==
'''Class definition:'''
<langsyntaxhighlight lang="j">coclass 'exampleClass'
 
exampleMethod=: monad define
Line 1,875 ⟶ 1,990:
)
 
exampleInstanceVariable=: 0</langsyntaxhighlight>
 
'''Instantiation:'''
<langsyntaxhighlight lang="j"> exampleObject=: conew 'exampleClass'</langsyntaxhighlight>
 
Note that all J system defined utilities designed specifically to work on classes and objects have names which begin with the prefix <code>co</code>.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class MyClass{
 
// instance variable
Line 1,901 ⟶ 2,015:
this.variable = 1;
}
}</langsyntaxhighlight>
Note: "this." in someMethod is optional. "variable = 1;" works also. If a parameter also named "variable" came into someMethod, using "this" specifies using the instance variable rather than the local method variable. Instantiate this class using:
<syntaxhighlight lang ="java">new MyClass();</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
JavaScript is [[wp:Prototype-based programming|prototype-based]], so it doesn't have classes per se. Thinking in classes when coding JavaScript will only hinder you in the long run, but here's an example of JavaScript OO:
 
<langsyntaxhighlight lang="javascript">//Constructor function.
function Car(brand, weight) {
this.brand = brand;
Line 1,932 ⟶ 2,045:
alert(cars[i].brand + " " + cars[i].weight + " " + cars[i].size + ", " +
(cars[i] instanceof Car) + " " + (cars[i] instanceof Truck));
}</langsyntaxhighlight>
The alerts shows us:
<pre>
Line 1,941 ⟶ 2,054:
 
===ES6===
<langsyntaxhighlight lang="javascript">class Car {
/**
* A few brands of cars
Line 2,017 ⟶ 2,130:
let myTruck = new Truck('Volvo', 2);
console.log(myTruck.formattedStats);
myTruck.drive(40);</langsyntaxhighlight>
 
Output:
Line 2,025 ⟶ 2,138:
Size: 2
A Volvo Truck drove 40cm</pre>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
Line 2,032 ⟶ 2,144:
Multiple dispatch is a core feature of the language.
 
<langsyntaxhighlight lang="julia">abstract type Mammal end
habitat(::Mammal) = "planet Earth"
 
Line 2,051 ⟶ 2,163:
for a in arr
println("Habitat of $a: ", habitat(a))
end</langsyntaxhighlight>
 
{{output}}
Line 2,057 ⟶ 2,169:
Habitat of a whale: ocean
Habitat of a wolf: planet Earth</pre>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">class MyClass(val myInt: Int) {
fun treble(): Int = myInt * 3
}
Line 2,066 ⟶ 2,177:
val mc = MyClass(24)
print("${mc.myInt}, ${mc.treble()}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,072 ⟶ 2,183:
24, 72
</pre>
 
=={{header|Lasso}}==
In Lasso, a "class" is termed a "type"
 
<syntaxhighlight lang="lasso">
<lang Lasso>
define mytype => type {
data
Line 2,095 ⟶ 2,205:
local(x = mytype)
#x->val = '99 Bottles of beer'
#x->asString // outputs 'has a value of: "99 Bottles of beer" and a rand number of "48"'</langsyntaxhighlight>
 
=={{header|LFE}}==
 
<langsyntaxhighlight lang="lisp">
(defmodule simple-object
(export all))
Line 2,131 ⟶ 2,240:
"Get a variable passed when constructing the object."
(funcall (get-method object 'species) object))
</syntaxhighlight>
</lang>
 
Usage from the LFE REPL:
<langsyntaxhighlight lang="lisp">
> (slurp '"simple-object.lfe")
#(ok simple-object)
Line 2,143 ⟶ 2,252:
> (get-species my-fish)
"Carp"
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
'''Class definition:'''
<langsyntaxhighlight lang="lingo">----------------------------------------
-- @desc Class "MyClass"
-- @file parent script "MyClass"
Line 2,165 ⟶ 2,273:
me._myvar = me._myvar * 2
put me._myvar
end</langsyntaxhighlight>
 
'''Instantiation:'''
<langsyntaxhighlight lang="lingo">foo = script("MyClass").new()
foo.doubleAndPrint()
-- 46</langsyntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">Section Header
 
+ name := SAMPLE;
Line 2,196 ⟶ 2,303:
sample := SAMPLE.clone;
sample.some_method;
);</langsyntaxhighlight>
 
=={{header|Logtalk}}==
The definition of classes in Logtalk require the use of meta-classes. In order to avoid infinite regression, we use here the usual trick of making a class an instance of itself. The class meta-class holds the constructor method, allowing the class to accept a message for creating a new instance. The class itself defines the methods and variables of its instances.
<langsyntaxhighlight lang="logtalk">:- object(metaclass,
instantiates(metaclass)).
 
Line 2,219 ⟶ 2,325:
:- private(state/1).
 
:- end_object.</langsyntaxhighlight>
A simple usage example after compiling and loading the above code:
<langsyntaxhighlight lang="logtalk">| ?- class::new(Instance, 1).
Instance = o1
yes
Line 2,227 ⟶ 2,333:
| ?- o1::method(Value).
Value = 1
yes</langsyntaxhighlight>
 
=={{header|Lua}}==
Classes in Lua are implemented with metatables. This doesn't implement a full system, but it gets the basic idea:
<langsyntaxhighlight lang="lua">myclass = setmetatable({
__index = function(z,i) return myclass[i] end, --this makes class variables a possibility
setvar = function(z, n) z.var = n end
Line 2,244 ⟶ 2,349:
instance:setvar(6)
 
print(instance.var) -->6</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Class zz {
module bb {
Line 2,351 ⟶ 2,455:
A(3)=zz()
A(3).bb
</lang>
 
Report {
there is no super like java super in M2000 when we use inheritance through classes
see Superclass (example SUP) which is something differnent
}
 
 
class Shape {
private:
super.X, super.Y
Function super.toString$(a=10) {
="Shape(" + str$(.super.X,"") + ", " + str$(.super.Y,"") + ")"
}
public:
Module final setPosition (px, py) {
.super.X <= px
.super.Y <= py
}
Function toString$() {
=.super.toString$()
}
}
class MoveShape {
Module MoveRelative(xr, yr) {
.super.X+=xr
.super.Y+=yr
}
}
class Circle as MoveShape as Shape {
private:
radius
public:
Module setRadius (r) {
.radius <= r
}
Function toString$() {
= .super.toString$() + ": Circle(" + str$(.radius,"") + ")"
}
}
 
class Rectangle as MoveShape as Shape {
private:
height, width
public:
Module MoveLeftSide (p as *Rectangle) {
\\ for same type objects private members are like public
for This, p {
.super.X<=..super.X+..width
.super.Y<=..super.Y
}
}
module setDimensions (h,w) {
.height <= h
.width <= w
}
Function toString$() {
= .super.toString$() + ": Rectangle(" + str$(.height,"") + " x " + str$(.width,"") + ")"
}
}
c =Circle()
r = Rectangle()
 
r.setPosition 1, 2
r.setDimensions 50, 50
c.setPosition 3, 4
c.setRadius 10
Print r.tostring$()
Print c.tostring$()
r.MoveRelative 100,100
c.MoveRelative -50,-50
Print r.tostring$()
Print c.tostring$()
 
Report {
wokring with pointers like in c++
pointers in M2000 are objects, so null pointer (pc->0&) isn't a zero, but an empty Group (object)
}
pc->circle()
pr->rectangle()
pr=>setPosition 1, 2
pr=>setDimensions 50, 50
pc=>setPosition 3, 4
pc=>setRadius 10
Print pr=>tostring$()
Print pc=>tostring$()
\\ we can open up to ten objects (from one to ten dots, normaly one to three)
\\ if we use nestef for object {} also we have up to ten objects in total
\\ every for object {} is an area for temporary definitions, after exit from brackets
\\ any new definition erased.
For pr, pc {
.MoveRelative 100,100
..MoveRelative -50,-50
Print .tostring$()
Print ..tostring$()
}
pr2->rectangle()
pr2=>SetDimensions 30, 30
pr2=>MoveLeftSide pr
Print pr2=>toString$()
 
</syntaxhighlight>
=={{header|MATLAB}}==
There are two ways to declare classes in MATLAB: with a classdef or without it. First you must create a folder named after the class type that you are defining with an "@" appended to the front, e.g. "@LinkedList", in your MATLAB root directory. In this folder you put all of the class methods and, if you have it, the classdef. Any MATLAB buitlin methods can be overloaded for any class you define. For example, if you want to overload the "+" operator, create an .m file in the class folder named "plus.m". Furthermore, all class variables have to be generated in the class constructor if a classdef is not going to be used.
Line 2,362 ⟶ 2,564:
 
GenericClass.m: Class Constructor
<langsyntaxhighlight MATLABlang="matlab">function GenericClassInstance = GenericClass(varargin)
 
if isempty(varargin) %No input arguments
Line 2,373 ⟶ 2,575:
GenericClassInstance = class(GenericClassInstance,'GenericClass');
end</langsyntaxhighlight>
getValue.m:
<langsyntaxhighlight MATLABlang="matlab">%Get function
function value = getValue(GenericClassInstance)
value = GenericClassInstance.classVariable;
end</langsyntaxhighlight>
setValue.m:
<langsyntaxhighlight MATLABlang="matlab">%Set function
function GenericClassInstance = setValue(GenericClassInstance,newValue)
GenericClassInstance.classVariable = newValue;
end</langsyntaxhighlight>
display.m: This method overloads the "disp()" command
<langsyntaxhighlight MATLABlang="matlab">function display(GenericClassInstance)
disp(sprintf('%f',GenericClassInstance.classVariable));
end</langsyntaxhighlight>
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> myClass = GenericClass(3)
3.000000
>> myClass = setValue(myClass,pi)
Line 2,398 ⟶ 2,600:
ans =
 
3.141592653589793</langsyntaxhighlight>
 
@GenericClass2
GenericClass2.m: This is the classdef, it includes the class constructor as well as class variables and methods.
<langsyntaxhighlight MATLABlang="matlab">classdef GenericClass2
properties
Line 2,429 ⟶ 2,631:
end %methods
end</langsyntaxhighlight>
getValue.m:
<langsyntaxhighlight MATLABlang="matlab">%Get function
function value = getValue(GenericClassInstance)
value = GenericClassInstance.classVariable;
end</langsyntaxhighlight>
display.m: This method overloads the "disp()" command
<langsyntaxhighlight MATLABlang="matlab">function display(GenericClassInstance)
disp(sprintf('%f',GenericClassInstance.classVariable));
end</langsyntaxhighlight>
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> myClass = GenericClass2(3)
3.000000
>> setValue(myClass,pi)
Line 2,448 ⟶ 2,650:
ans =
 
3.141592653589793</langsyntaxhighlight>
 
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">// MiniScript is prototype based
Weapon = { "name": "Sword", "damage": 3 }
Weapon.slice = function()
Line 2,462 ⟶ 2,662:
wep.name = "Lance"
 
wep.slice</langsyntaxhighlight>
=={{header|MiniZinc}}==
MiniZinc does not have classes, but they can be simulated using functions with constraints:
<syntaxhighlight lang="minizinc">% define a Rectangle "class"
var int: Rectangle(var int: width, var int: height) =
let {
var int: this;
constraint Type(this) = Rectangle; %define the "type" of the instance
%define some "instance methods"
constraint area(this) = width*height;
constraint width(this) = width;
constraint height(this) = height;
} in this;
%this enum should contain the list of class names
enum Type = {Rectangle};
function var Type: Type(var int:a);
 
%declare the "instance methods"
function var int: area(var int:this) = let {var int:result;} in result;
function var int: height(var int:a) = let {var int:result;} in result;
function var int: width(var int:a) = let {var int:result;} in result;
 
%create an instance of the "class"
var int: rect = Rectangle(3,4);
var int: area1 = area(rect);
 
solve satisfy;
 
% print the area of the rectangle
output [show(area1),"\n"];</syntaxhighlight>
=={{header|Nanoquery}}==
<langsyntaxhighlight lang="nanoquery">class MyClass
declare name
Line 2,482 ⟶ 2,711:
// display the name value
println inst.getName()</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">public class MyClass
{
public this() { } // the constructor in Nemerle is always named 'this'
Line 2,503 ⟶ 2,731:
def myInstance = MyClass(); // no 'new' keyword needed
myInstance.MyVariable = 42; // set MyVariable
System.Console.WriteLine($"My variable is $(myInstance.MyVariable)") // get MyVariable</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang="rexx">class ClassExample
 
properties private -- class scope
Line 2,536 ⟶ 2,763:
method test(s=boolean)
mies = 3
say s mies</langsyntaxhighlight>
 
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">type MyClass = object
name: int
 
Line 2,567 ⟶ 2,792:
echo person1.name, " ", person1.gender, " ", person1.age # Jane female 50
var person2 = initMyOtherClass("John", male, 23)
echo person2.name, " ", person2.gender, " ", person2.age # John male 23</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
{{works with|OO2C|2.1.11}}
<langsyntaxhighlight lang="oberon2">MODULE M;
 
TYPE
Line 2,592 ⟶ 2,816:
END Increment;
 
END M.</langsyntaxhighlight>
 
Exported procedures are marked with an asterisk (*). There is nothing special about the constructor New, it is just a function that returns a new object of type T. The name of the method receiver can also be chosen freely. INC is a predeclared procedure that increments its argument.
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">bundle Default {
class MyClass {
@var : Int;
Line 2,629 ⟶ 2,852:
}
}
}</langsyntaxhighlight>
 
=={{header|Object Pascal}}==
{{works with|Turbo Pascal|6.0}}
:''Note: This is not part of standard Pascal, but Turbo Pascal specific''
 
<langsyntaxhighlight lang="pascal">type
MyClass = object
variable: integer;
Line 2,669 ⟶ 2,891:
instance.done;
dispose(pInstance, done);
end;</langsyntaxhighlight>
 
=={{header|Objective-C}}==
{{works with|GCC}}
Line 2,676 ⟶ 2,897:
{{works with|GNUstep}}
Interface:
<langsyntaxhighlight lang="objc">// There are no class variables, so static variables are used.
static int myClassVariable = 0;
 
Line 2,686 ⟶ 2,907:
- (int)variable; // Typical accessor - you should use the same name as the variable
 
@end</langsyntaxhighlight>
 
Implementation:
 
<langsyntaxhighlight lang="objc">@implementation MyClass
 
// Was not declared because init is defined in NSObject
Line 2,706 ⟶ 2,927:
}
 
@end</langsyntaxhighlight>
 
Using the class:
 
<langsyntaxhighlight lang="objc">// Creating an instance
MyClass *mc = [[MyClass alloc] init];
 
// Sending a message
[mc variable];</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">class my_class =
object (self)
val mutable variable = 0
method some_method = variable <- 1
end</langsyntaxhighlight>
 
Using the class:
Line 2,730 ⟶ 2,950:
- : unit = ()
</pre>
 
=={{header|Oforth}}==
Class creation
<langsyntaxhighlight Oforthlang="oforth">Object Class new: MyClass(att)
MyClass method: initialize(v) v := att ;</langsyntaxhighlight>
 
Usage : instantiation
<langsyntaxhighlight Oforthlang="oforth">MyClass new("some value")</langsyntaxhighlight>
 
=={{header|Ol}}==
Otus Lisp have no classes support.
 
=={{header|ooRexx}}==
ooRexx classes are defined using directives. Only methods of the class can directly access instance variables to avoid fragile base class
problems, methods can only access variables at the level of the class hierarchy they are defined. ::attribute directives create setter and getter methods that allow instance variables to be accessed in other contexts.
 
<langsyntaxhighlight ooRexxlang="oorexx">p = .point~new
c = .circle~new
 
Line 2,774 ⟶ 2,991:
::method print
expose radius
say "A circle of radius" radius "centered at location ("||self~x","self~y")"</langsyntaxhighlight>
 
=={{header|OxygenBasic}}==
Example of a dynamic object. (statically defined objects do not require specific constructors and destructors.)
 
Parameter polymorphism is supported both by method overloading and also by automatic type conversion between integers, floats, strings and other primitives.
 
<langsyntaxhighlight lang="oxygenbasic">
 
Class MyObject
class SuperString
 
static int count 'statics are private
indexbase 1
 
int a,b,c
union
bstring s
sys bs
sys *y
int *i
byte *b
float *f
end union
 
method spaceconstructor(sysint npa,pb,pc)
s=space n "constructed"
a=pa : b=pb : c=pc
count++
end method
 
method deletedestructor()
del s
freememory bs : bs=0
end method
 
method clearsum() as int
return a+b+c
sys j, le=length
if le then
for j=1 to le : b[j]=0 : next
end if
end method
 
method length() as sys
if bs then return i[0]
end method
 
method resize(sys n)
sys le=length
if n<le
s=left s,n
elseif n>le
s+=nuls n-le
end if
end method
 
method fill(string f)
sys j, ls=length, lf=len f
for j=1 to ls step lf
mid s,j,f
next
end method
 
method constructor()
end method
 
method destructor
delete
end method
 
end class
 
new MyObject v(2,4,6)
 
print "Sum: " v.sum
'#recordof SuperString
 
'=====
'TESTS
'=====
 
new SuperString ss
'
ss.space 100
ss.resize 8
ss.fill "abc"
'
print ss.s 'result abcabcab
print ss.b[3] 'result 99: ascii for 'c'
'
del ss
</lang>
 
del v
</syntaxhighlight>
=={{header|Oz}}==
Classes are created at runtime and first-class values.
<langsyntaxhighlight lang="oz">declare
class Something
feat
Line 2,884 ⟶ 3,050:
 
%% call a method
{Object increase}</langsyntaxhighlight>
 
=={{header|Pascal}}==
See [[Classes#Delphi | Delphi]]
 
=={{header|Perl}}==
{{works with|Perl|5.8.6}}
The implementation (there are no declarations) of a class using the [http://search.cpan.org/perldoc?perlobj standard] object system:
<langsyntaxhighlight lang="perl">{
# a class is a package (i.e. a namespace) with methods in it
package MyClass;
Line 2,910 ⟶ 3,074:
$self->{variable} = 1;
}
}</langsyntaxhighlight>
 
This is the same using the [http://search.cpan.org/perldoc?Moose Moose] object system:
<langsyntaxhighlight lang="perl">{
package MyClass;
use Moose;
Line 2,924 ⟶ 3,088:
$self->variable(1);
}
}</langsyntaxhighlight>
 
This is the same class using the [http://search.cpan.org/perldoc?MooseX::Declare MooseX::Declare] extention:
<langsyntaxhighlight lang="perl">use MooseX::Declare;
class MyClass {
has 'variable' => (is => 'rw', default => 0);
Line 2,933 ⟶ 3,097:
$self->variable(1);
}
}</langsyntaxhighlight>
 
All of the above classes can be used the same way:
<langsyntaxhighlight lang="perl">my $instance = MyClass->new; # invoke constructor method
 
$instance->some_method; # invoke method on object instance
# instance deallocates when the last reference falls out of scope</langsyntaxhighlight>
=={{header|Phix}}==
 
{{libheader|Phix/Class}}
=={{header|Perl 6}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
{{works with|Rakudo|2015.12}}
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (else cffi namespaces error, classes not supported by pwa/p2js anyway)</span>
<lang perl6>class Camel { has Int $.humps = 1; }
<span style="color: #7060A8;">requires</span> <span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.2"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (free up the temp used in the v.show() call)</span>
 
my Camel $a .= new;
<span style="color: #008080;">class</span> <span style="color: #000000;">five</span> <span style="color: #008080;">nullable</span>
say $a.humps; # Automatically generated accessor method.
<span style="color: #008080;">private</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span>
 
<span style="color: #008080;">function</span> <span style="color: #000000;">get_n</span><span style="color: #0000FF;">()</span>
my Camel $b .= new: humps => 2;
<span style="color: #008080;">return</span> <span style="color: #000000;">n</span>
say $b.humps;</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
<span style="color: #008080;">procedure</span> <span style="color: #000000;">set_n</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
A more complex example:
<span style="color: #7060A8;">this</span><span style="color: #0000FF;">.</span><span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<lang perl6>class Butterfly {
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show</span><span style="color: #0000FF;">()</span>
has Int $!age; # With the ! twigil, no public accessor method is generated
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"show: n is %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">})</span>
has Str $.name;
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
has Str $.color;
<span style="color: #008080;">function</span> <span style="color: #000000;">five</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
has Bool $.wings;
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"constructor five(%d) called\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
 
<span style="color: #7060A8;">this</span><span style="color: #0000FF;">.</span><span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span>
submethod BUILD(:$!name = 'Camelia', :$!age = 2, :$!color = 'pink') {
<span style="color: #008080;">return</span> <span style="color: #7060A8;">this</span>
# BUILD is called by bless. Its primary use is to to control
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
# object initialization.
<span style="color: #008080;">procedure</span> <span style="color: #0000FF;">~</span><span style="color: #000000;">five</span><span style="color: #0000FF;">()</span>
$!wings = $!age > 1;
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"destructor ~five(%d) called\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
}
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">class</span>
method flap() {
<span style="color: #000000;">five</span> <span style="color: #000000;">v</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new</span><span style="color: #0000FF;">({</span><span style="color: #000000;">5</span><span style="color: #0000FF;">})</span>
say ($.wings
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">.</span><span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
?? 'Watch out for that hurricane!'
<span style="color: #000000;">v</span><span style="color: #0000FF;">.</span><span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">6</span>
!! 'No wings to flap.');
<span style="color: #000000;">v</span><span style="color: #0000FF;">.</span><span style="color: #000000;">show</span><span style="color: #0000FF;">()</span>
}
<span style="color: #000000;">v</span><span style="color: #0000FF;">=</span><span style="color: #004600;">NULL</span>
}
<!--</syntaxhighlight>-->
 
{{out}}
my Butterfly $a .= new: age => 5;
<pre>
say "Name: {$a.name}, Color: {$a.color}";
constructor five(5) called
$a.flap;
show: n is 6
 
destructor ~five(6) called
my Butterfly $b .= new(name => 'Osgood', age => 4);
</pre>
say "Name: {$b.name}, Color: {$b.color}";
Obviously when n is public then neither get_n() nor set_n() is needed.<br>
$b.flap;</lang>
When there is no constructor method, new() args get assigned in order, so here n would still become 5.
 
=={{header|PHL}}==
 
<langsyntaxhighlight lang="phl">module classes;
 
extern printf;
Line 3,004 ⟶ 3,168:
printf("obj.myField: %i\n", obj::get_myField);
return 0;
]</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">class MyClass {
public static $classVar;
public $instanceVar; // can also initialize it here
Line 3,018 ⟶ 3,181:
}
}
$myObj = new MyClass();</langsyntaxhighlight>
<!-- TODO ;; 2008-01-24 07:35 fill this in when i get a few spare moments
/*
Line 3,038 ⟶ 3,201:
*/
-->
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(class +Rectangle)
# dx dy
 
Line 3,047 ⟶ 3,209:
 
(println # Create a rectangle, and print its area
(area> (new '(+Rectangle) 'dx 3 'dy 4)) )</langsyntaxhighlight>
 
=={{header|Pop11}}==
Object system is implemented as a library, so we must first load it.
<langsyntaxhighlight lang="pop11">uses objectclass;
define :class MyClass;
slot value = 1;
enddefine;</langsyntaxhighlight>
 
Defining class MyClass automatically defines two constructors, newMyClass and consMyClass and slot (instance variable) accessors, so we can immediately start using our new class:
 
<langsyntaxhighlight lang="pop11">;;; Construct instance with default slot values
lvars instance1 = newMyClass();
;;; Construct instance with explicitely given slot values
Line 3,070 ⟶ 3,231:
12 -> value(instance1);
;;; Print it
value(instance1) =></langsyntaxhighlight>
 
We can add methods at any time (even after creating an instance):
 
<langsyntaxhighlight lang="pop11">define :method reset(x : MyClass);
0 -> value(x);
enddefine;
reset(instance1);
;;; Print it
instance1 =></langsyntaxhighlight>
=={{header|Portugol}}==
{{trans|D}}
<syntaxhighlight lang="portugol">
programa {
inclua biblioteca Objetos --> obj
 
// "constructor" returns address of object
funcao inteiro my_class_new(inteiro value) {
inteiro this = obj.criar_objeto()
obj.atribuir_propriedade(this, "variable", value) // add property to object
retorne this
}
 
// "method" takes the address returned by criar_objeto
funcao my_class_some_method(inteiro this) {
my_class_set_variable(this, 1)
}
 
// "setter"
funcao my_class_set_variable(inteiro this, inteiro value) {
obj.atribuir_propriedade(this, "variable", value)
}
 
// "getter"
funcao inteiro my_class_get_variable(inteiro this) {
retorne obj.obter_propriedade_tipo_inteiro(this, "variable")
}
funcao inicio() {
inteiro this = my_class_new(0)
 
escreva("variable = ", my_class_get_variable(this), "\n")
 
my_class_some_method(this)
 
escreva("variable = ", my_class_get_variable(this), "\n")
 
my_class_set_variable(this, 99)
 
escreva("variable = ", my_class_get_variable(this), "\n")
 
obj.liberar_objeto(this)
}
}
 
</syntaxhighlight>
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
Prior to PowerShell 5, native class definition was not supported in PowerShell. But you could define classes in PowerShell using C#, JavaScript, or VisualBasic.
<langsyntaxhighlight lang="powershell">
Add-Type -Language CSharp -TypeDefinition @'
public class MyClass
Line 3,113 ⟶ 3,319:
}
'@
</syntaxhighlight>
</lang>
{{works with|PowerShell|5}}
<br>
<b>Basic syntax</b>
<syntaxhighlight lang="powershell">
<lang PowerShell>
class MyClass
{
Line 3,135 ⟶ 3,341:
}
}
</syntaxhighlight>
</lang>
<b>Example class</b>
<syntaxhighlight lang="powershell">
<lang PowerShell>
class Banana
{
Line 3,171 ⟶ 3,377:
}
}
</syntaxhighlight>
</lang>
<b>Using the example class</b>
<syntaxhighlight lang="powershell">
<lang PowerShell>
$MyBanana = [banana]::New()
$YourBanana = [banana]::New( $True )
Line 3,179 ⟶ 3,385:
If ( -not $MyBanana.IsReadyToEat() -and $YourBanana.IsReadyToEat() )
{ $MySecondBanana = $YourBanana }
</syntaxhighlight>
</lang>
 
=={{header|Processing}}==
<langsyntaxhighlight lang="java">class ProgrammingLanguage
{
// instance variable:
Line 3,198 ⟶ 3,403:
// the method has no argument or local variable called "name", so we can omit the "this"
}
}</langsyntaxhighlight>
How to use it:
<langsyntaxhighlight lang="java">// instantiate the class:
ProgrammingLanguage processing = new ProgrammingLanguage("Processing");
 
// call the method:
processing.sayHello();</langsyntaxhighlight>
{{out}}
<pre>Hello from the programming language Processing</pre>
 
=={{header|PureBasic}}==
===Generic version===
<langsyntaxhighlight PureBasiclang="purebasic">Interface OO_Interface ; Interface for any value of this type
Get.i()
Set(Value.i)
Line 3,265 ⟶ 3,469:
*Foo\Set(341)
MessageRequester("Info", "Foo = " + *Foo\ToString() )
*Foo\Destroy()</langsyntaxhighlight>
 
===Simple OOP Version===
Using the open-source precompiler [http://www.development-lounge.de/viewtopic.php?t=5915 SimpleOOP].
<langsyntaxhighlight PureBasiclang="purebasic">Class Foo
Private Value.i
Line 3,298 ⟶ 3,502:
*Demo.foo = NewObject.foo()
*Demo\Set(4)
MessageRequester("Info", "Val= " + *Demo\ToString())</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">class MyClass:
name2 = 2 # Class attribute
 
Line 3,338 ⟶ 3,541:
print person1.age # Raises AttributeError exception!
person2 = MyOtherClass("Jane", "Female", 23)
print person2.name, person2.gender, person2.age # "Jane Female 23"</langsyntaxhighlight>
 
Python allows for very flexible argument passing including normal named parameters, defaulted/optional named parameters, up to one "varargs" tuple, and any number of keywords arguments (which are all passed in the form of a single dictionary (associative array), and any non-ambiguous combination of these). All types of argument passing for functions can also be used for object instantiation/initialization (passed to the special ''__init__()'' method) as shown.
Line 3,344 ⟶ 3,547:
New-style classes inherit from "object" or any descendant of the "object" class:
 
<langsyntaxhighlight lang="python">class MyClass(object):
...</langsyntaxhighlight>
 
These "new-style" classes support some features which were unavailable in "classic classes". New features include a ''__new__()'' with lower level control over object instantiation, metaclass support, static methods, class methods, "properties" (managed attributes) and "slots" (attribute restrictions).
 
=={{header|R}}==
R has (at least) 5 different object oriented systems. S3 and S4 correspond to different versions of the S language, from which R was derived. See, for example, [http://www.r-project.org/conferences/useR-2004/Keynotes/Leisch.pdf this presentation by Freidrich Leisch] for a more thorough introduction to S3 and S4 classes. Both these class systems are in use, and ship with the standard R distribution. The [http://www.omegahat.org/RSOOP/ OOP], [http://cran.r-project.org/web/packages/R.oo/index.html R.oo] and [http://cran.r-project.org/web/packages/proto/index.html proto] packages provide other systems.
Line 3,354 ⟶ 3,556:
===S3===
S3 provides a very simple class system designed to be easily used interactively.
<langsyntaxhighlight Rlang="r">#You define a class simply by setting the class attribute of an object
circS3 <- list(radius=5.5, centre=c(3, 4.2))
class(circS3) <- "circle"
Line 3,366 ⟶ 3,568:
type="l", ...)
}
plot(circS3)</langsyntaxhighlight>
 
===S4===
S4 is a more formal class system that provides validity checking and a way to define different methods for different input signatures.
<langsyntaxhighlight Rlang="r">setClass("circle",
representation(
radius="numeric",
Line 3,393 ⟶ 3,595:
type="l", ...)
})
plot(circS4)</langsyntaxhighlight>
 
=={{header|Racket}}==
 
Racket programs heavily use functions, but classes and objects are available as well:
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 3,415 ⟶ 3,616:
;; constructing an instance
(new fish% [size 50])
</syntaxhighlight>
</lang>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" line>class Camel { has Int $.humps = 1; }
 
my Camel $a .= new;
say $a.humps; # Automatically generated accessor method.
 
my Camel $b .= new: humps => 2;
say $b.humps;</syntaxhighlight>
 
A more complex example:
 
<syntaxhighlight lang="raku" line>class Butterfly {
has Int $!age; # With the ! twigil, no public accessor method is generated
has Str $.name;
has Str $.color;
has Bool $.wings;
 
submethod BUILD(:$!name = 'Camelia', :$!age = 2, :$!color = 'pink') {
# BUILD is called by bless. Its primary use is to to control
# object initialization.
$!wings = $!age > 1;
}
 
method flap() {
say ($.wings
?? 'Watch out for that hurricane!'
!! 'No wings to flap.');
}
}
 
my Butterfly $a .= new: age => 5;
say "Name: {$a.name}, Color: {$a.color}";
$a.flap;
 
my Butterfly $b .= new(name => 'Osgood', age => 4);
say "Name: {$b.name}, Color: {$b.color}";
$b.flap;</syntaxhighlight>
=={{header|RapidQ}}==
<langsyntaxhighlight lang="rapidq">TYPE MyClass EXTENDS QObject
Variable AS INTEGER
 
Line 3,434 ⟶ 3,673:
 
' invoke the method
instance.someMethod</langsyntaxhighlight>
 
=={{header|Raven}}==
Build classes:
<langsyntaxhighlight lang="raven">class Alpha
'I am Alpha.' as greeting
define say_hello
Line 3,444 ⟶ 3,682:
 
class Beta extend Alpha
'I am Beta!' as greeting</langsyntaxhighlight>
 
Execute classes to create objects:
<langsyntaxhighlight lang="raven">Alpha as alpha
Beta as beta</langsyntaxhighlight>
 
Call methods:
<langsyntaxhighlight lang="raven">alpha.say_hello
beta.say_hello</langsyntaxhighlight>
 
Result:
<langsyntaxhighlight lang="raven">I am Alpha.
I am Beta!</langsyntaxhighlight>
 
=={{header|REALbasic}}==
This class "contains" a number ('TheNumber'). The Number methods allow read and write access to the number, and provide an example of method overloading as well as use of the "Assigns" keyword.
 
<syntaxhighlight lang="vb">
<lang vb>
Class NumberContainer
Private TheNumber As Integer
Line 3,476 ⟶ 3,713:
End Sub
End Class
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="vb">
<lang vb>
Dim num As New NumberContainer(1) ' call the constructor
num.Number = num.Number + 5 ' call both Number methods
</syntaxhighlight>
</lang>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">rebol [
Title: "Classes"
URL: http://rosettacode.org/wiki/Classes
Line 3,522 ⟶ 3,758:
 
print "Howdy, Pecos!" pecos/hi
print "Tell us about yourself?" pecos/boast</langsyntaxhighlight>
 
{{out}}
Line 3,535 ⟶ 3,771:
 
[[wp:Pecos_Bill|Context...]]
 
=={{header|Rhovas}}==
 
Rhovas has both structs and classes. [https://rhovas.dev/learn/tour/#structs Structs] are used for structured data (e.g. Kotlin data classes or Java records) however have some additional restrictions like fields always being part of the API (see earlier link).
 
An example of a struct for (<code>Decimal</code>) <code>Vector</code>s. Some notes:
* Fields are often mutable (<code>var</code>) and use mutability permissions to represent immutable structs rather than defining immutable fields directly.
* Methods are defined with a first parameter of <code>this</code>. The type is optional, but can be specified to support more nuanced subtypes as needed (e.g. with generics).
 
<syntaxhighlight lang="scala">
struct Vector {
var x: Decimal;
var y: Decimal;
 
func magnitude(this): Decimal {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
}
</syntaxhighlight>
 
The next step up from structs are classes. [https://rhovas.dev/learn/tour/#classes Classes] support the full range of Object-Oriented capabilities (e.g. encapsulation and inheritance) and are primarily for maintaining invariants.
 
For example, a hypothetical <code>UnitVector</code> class has an invariant between <code>x</code> and <code>y</code>, requiring a direction with non-zero magnitude. One option is to use a class to maintain that invariant:
* The example below uses immutable fields and validates the invariant in the constructor, but in practice there would be mutation involved.
* <code>require direct.x != 0.0 ...</code> validates preconditions for the direction <code>Vector</code>.
* <code>this { x: ..., y: ... };</code> initializes object fields in a single action to prevent partially constructed instances from being leaked (which would break invariants) and is less restrictive than similar constructors in Kotlin/Java.
 
<syntaxhighlight lang="scala">
class UnitVector {
val x: Decimal;
val y: Decimal;
 
init(direction: Vector) {
require direction.x != 0.0 || direction.y != 0.0;
val magnitude = direction.magnitude();
this { x: direction.x / magnitude, y: direction.y / magnitude };
}
}
</syntaxhighlight>
 
=={{header|Ring}}==
Line 3,540 ⟶ 3,815:
Simple program to define class and create an object
 
<langsyntaxhighlight lang="ring">
New point { x=10 y=20 z=30 print() }
Class Point x y z func print see x + nl + y + nl + z + nl
</syntaxhighlight>
</lang>
 
The previous program can be written in another way
 
<langsyntaxhighlight lang="ring">
New point # create new object using the point class
{ # access the new object attributes and methods
Line 3,563 ⟶ 3,838:
y + nl + # print the y attribute
z + nl # print the z attribute
</syntaxhighlight>
</lang>
 
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class MyClass
def initialize
Line 3,580 ⟶ 3,853:
my_class = MyClass.new #allocates an object and calls it's initialize method, then returns it.
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
struct MyClass {
variable: i32, // member variable = instance variable
Line 3,606 ⟶ 3,878:
 
// Create an instance in the heap.
let mut p_instance = Box::<_>::new(MyClass::new());
 
// Invoke method on both istances,
Line 3,614 ⟶ 3,886:
// Both instances are automatically deleted when their scope ends.
}
</syntaxhighlight>
</lang>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class CLASSTEST is
readonly attr x:INT; -- give a public getter, not a setter
private attr y:INT; -- no getter, no setter
Line 3,637 ⟶ 3,908:
return y + s;
end;
end;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sather">class MAIN is
main is
test ::= #CLASSTEST(1, 2, 3);
Line 3,650 ⟶ 3,921:
#OUT + test.getPrivateY(0) + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
Scala can be highly object-oriented and if so the task is trivial. In some cases the constructor and instance variables do not have to be explicitly declared; this example shows two ways each to make constructors and instance variables.
<langsyntaxhighlight Scalalang="scala">/** This class implicitly includes a constructor which accepts an Int and
* creates "val variable1: Int" with that value.
*/
Line 3,677 ⟶ 3,947:
println(m.myMethod) // prints 0
println(n.myMethod) // prints 3
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
From [http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-20.html#%_sec_3.1.1 Structure and Interpretation of Computer Programs]
<langsyntaxhighlight Schemelang="scheme"> (define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
Line 3,694 ⟶ 3,963:
(else (error "Unknown request -- MAKE-ACCOUNT"
m))))
dispatch)</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">class MyClass(instance_var) {
method add(num) {
instance_var += num;
Line 3,705 ⟶ 3,973:
var obj = MyClass(3); # `instance_var` will be set to 3
obj.add(5); # calls the add() method
say obj.instance_var; # prints the value of `instance_var`: 8</langsyntaxhighlight>
 
=={{header|Simula}}==
As the first object-oriented language, Simula introduced both the term <tt>class</tt> and the <tt>object.method(arguments)</tt> syntax that many other languages on this page employ. Notice that the object must be declared using <tt>ref</tt> (reference, i.e. pointer) before it can be instantiated.
<langsyntaxhighlight lang="simula">BEGIN
CLASS MyClass(instanceVariable);
INTEGER instanceVariable;
Line 3,727 ⟶ 3,994:
myObject :- NEW MyClass(5);
myObject.doMyMethod(2)
END</langsyntaxhighlight>
{{out}}
<pre> 5 + 2 = 7</pre>
 
=={{header|Slate}}==
Slate objects operate as prototypes with multi-methods:
<langsyntaxhighlight lang="slate">prototypes define: #MyPrototype &parents: {Cloneable} &slots: #(instanceVar).
MyPrototype traits addSlot: #classVar.
 
Line 3,744 ⟶ 4,010:
[
x instanceVar = 1 /\ (x classVar = 3)
].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">Object subclass: #MyClass
instanceVariableNames: 'instanceVar'
classVariableNames: 'classVar'
Line 3,761 ⟶ 4,026:
^self instanceVar = 1; classVar = 3 ! !
 
MyClass new someMethod!</langsyntaxhighlight>
 
=={{header|SuperCollider}}==
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
 
 
Line 3,800 ⟶ 4,064:
 
 
</syntaxhighlight>
</lang>
 
Call it:
 
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
SpecialObject.randomizeAll;
a = SpecialObject(8);
a.coordinates;
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">class MyClass{
 
// stored property
Line 3,829 ⟶ 4,092:
self.variable = 1
}
}</langsyntaxhighlight>
Instantiate this class using:
<syntaxhighlight lang ="swift">MyClass()</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<langsyntaxhighlight Tcllang="tcl">package require TclOO
oo::class create summation {
variable v
Line 3,856 ⟶ 4,118:
puts "Add $i to get [$sum add $i]"
}
$sum destroy</langsyntaxhighlight>
 
=={{header|TIScript}}==
TIScript is [[wp:Prototype-based programming|prototype-based]] and yet it has classes. Object that was created as an instance of one class can be transformed to the instance of another class by changing its obj.prototype field.
 
<langsyntaxhighlight lang="javascript">class Car
{
//Constructor function.
Line 3,895 ⟶ 4,156:
stdout.printf("#%d %s $%d %v %v, %v %v", i, car.brand, car.price, car.weight, car.size,
car instanceof Car, car instanceof Truck);
}</langsyntaxhighlight>
{{out}} from console :
<pre>
Line 3,901 ⟶ 4,162:
#2 Volvo 2000 $30000 2, true true
</pre>
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
 
class Point : {
x: Double(),
y: Double(),
@init: (λ v Vector<Double>() (= x (get v 0)) (= y (get v 1))),
print: (λ (textout "Point(" x "; " y ")\n" ))
}
 
MainModule: {
v_: [[1.0, 2.0], [3.0, 4.0]],
 
_start: (λ
// creating an instance of class
(with pt Point([5.0, 6.0])
// calling a class' method
(print pt)
)
 
// creating several instances using data deserialization
(with v Vector<Point>(v_)
(for p in v do (print p))
) )
}</syntaxhighlight>
{{out}}
<pre>
Point(5; 6)
Point(1; 2)
Point(3; 4)
</pre>
=={{header|TXR}}==
<langsyntaxhighlight lang="txrlisp">(defstruct shape ()
cached-area
 
Line 3,926 ⟶ 4,217:
 
(:method calc-area (self)
(* self.length self.length)))</langsyntaxhighlight>
 
{{out}}
Line 3,948 ⟶ 4,239:
* There must be no whitespace around the dot: <code>(a . b)</code> is the consing dot whereas <code>(a.b)</code> is the syntax <code>((qref a b))</code>.
* Ambiguity with floating-point numbers isn't allowed. For instance, <code>a.b.1</code> elicits an error from the parser (lexical scanner actually).
 
=={{header|UNIX Shell}}==
{{works with|ksh93}}
ksh93 has "type variables" which essentially declares a class.
<langsyntaxhighlight lang="bash">typeset -T Summation_t=(
integer sum
 
Line 3,970 ⟶ 4,260:
s.add $i
done
print ${s.sum}</langsyntaxhighlight>
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">public class MyClass : Object {
// Instance variable
public int variable;
Line 3,995 ⟶ 4,284:
instance.variable = 84;
print("%d\n", instance.variable);
}</langsyntaxhighlight>
 
=={{header|VBA}}==
===Defining a class===
Line 4,007 ⟶ 4,295:
This is the contents of a class module "Foo" (like in the Visual Basic .NET example below):
 
<langsyntaxhighlight lang="vb">Private Const m_default = 10
Private m_bar As Integer
 
Line 4,037 ⟶ 4,325:
'Note: instead of using the instance variable m_bar we could refer to the Bar property of this object using the special word "Me":
' MultiplyBar = Me.Bar * x
End Function</langsyntaxhighlight>
 
===Using an object===
Objects (e.g. of class Foo) are created and used in "normal" modules.
<langsyntaxhighlight lang="vb">Public Sub foodemo()
'declare and create separately
Dim f As Foo
Line 4,077 ⟶ 4,365:
'this will trigger one or two "object destroyed" messages
'depending on whether f0 was created...
End Sub</langsyntaxhighlight>
 
{{out}}
Line 4,089 ⟶ 4,377:
---object destroyed---
</pre>
 
=={{header|Visual Basic .NET}}==
===Defining a class===
<langsyntaxhighlight lang="vbnet">Class Foo
Private m_Bar As Integer
 
Line 4,120 ⟶ 4,407:
End Function
 
End Class</langsyntaxhighlight>
 
===Using an object===
<langsyntaxhighlight lang="vbnet">'Declare and create separately
Dim foo1 As Foo
foo1 = New Foo
Line 4,144 ⟶ 4,431:
'Reading/writing properties
Console.WriteLine(foo4.Bar)
foo4.Bar = 1000</langsyntaxhighlight>
 
=={{header|Visual FoxPro}}==
Visual FoxPro has a large number of base classes - Session is one of them.
<langsyntaxhighlight lang="vfp">
LOCAL o1 As MyClass, o2 As MyClass
*!* Instantiate o1
Line 4,177 ⟶ 4,463:
ENDPROC
ENDDEFINE
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,183 ⟶ 4,469:
Instance 2
</pre>
=={{header|Wren}}==
<syntaxhighlight lang="wren">class Bear {
// Constructs a Bear instance passing it a name
// which is stored in the field _name
// automatically created by Wren.
construct new(name) { _name = name }
// Property to get the name
name { _name }
 
// Method to make a noise.
makeNoise() { System.print("Growl!") }
}
 
// Create a new Bear instance and assign a reference to it
// to the variable b.
var b = Bear.new("Bruno")
 
// Print the bear's name.
System.print("The bear is called %(b.name).")
// Make a noise.
b.makeNoise()</syntaxhighlight>
 
{{out}}
<pre>
The bear is called Bruno.
Growl!
</pre>
 
=={{header|X86-64 Assembly}}==
===UASM 2.52===
Details about the UASM class extention can be found [http://www.terraspace.co.uk/uasm252_ext.pdf here].
<syntaxhighlight lang="asm">
option casemap:none
 
ifndef __SOMECLASS_CLASS__
__SOMECLASS_CLASS__ equ 1
 
;; Once again, HeapAlloc/Free is REQUIRED by the class extention for windows.
;; Malloc/Free are used by Linux and OSX. So the function prototypes have to
;; be defined somewhere. If you have include files where they're defined, just
;; include them in the usual way and remove the option dllimports.
if @Platform eq 1 ;; Windows 64
;; include windows.inc
;; includelib kernel32.lib
option dllimport:<kernel32>
HeapAlloc proto :qword, :dword, :qword
HeapFree proto :qword, :dword, :qword
ExitProcess proto :dword
GetProcessHeap proto
option dllimport:none
exit equ ExitProcess
elseif @Platform eq 3 ;; Linux 64
;;include libc.inc
malloc proto SYSTEMV :qword
free proto SYSTEMV :qword
exit proto SYSTEMV :dword
endif
 
printf proto :qword, :VARARG
 
CLASS someClass
CMETHOD someMethod
ENDMETHODS
var dd ?
ENDCLASS
 
;; The OS' ABI has an effect on this class extention. That is, the class self pointetr
;; is usually refferenced in the first arg register. So for Windows it would be rcx and
;; Linux would be rdi. So to write code that will assemble on both we use a register
;; that ISN'T used to pass arguments in either ABI(Not sure about OSX's ABI however)
METHOD someClass, Init, <VOIDARG>, <>, a:dword
mov rbx, thisPtr
assume rbx:ptr someClass
mov [rbx].var, a
mov rax, rbx
assume rbx:nothing
ret
ENDMETHOD
 
METHOD someClass, someMethod, <dword>, <>
mov rbx, thisPtr
assume rbx:ptr someClass
mov eax, [rbx].var
assume rbx:nothing
ret
ENDMETHOD
 
METHOD someClass, Destroy, <VOIDARG>, <>
ret
ENDMETHOD
endif ;; __CLASS_CLASS_
 
.code
main proc
local meh:ptr someClass
;; Create a new instance of someClass with an arg of 7
mov meh, _NEW(someClass, 7)
meh->someMethod() ;;Get meh->var value and return it in RAX
invoke printf, CSTR("class->someMethod = %i",10), rax
_DELETE(meh) ;; DIIIIIIIE!
invoke exit, 0 ;; Crashy crashy without it.
ret
main endp
 
end
</syntaxhighlight>
{{out}}
<pre>
class->someMethod = 7
</pre>
=={{header|XBS}}==
<syntaxhighlight lang="xbs">class Person {
construct=func(self,Name,Age,Gender){
self:Name=Name;
self:Age=Age;
self:Gender=Gender;
}{Name="John",Age=20,Gender="Male"};
ToString=func(self){
send self.Name+" ("+self.Gender+"): Age "+self.Age;
}
}
 
set John = new Person with [];
log(John::ToString());
set Jane = new Person with ["Jane",20,"Female"]
log(Jane::ToString());</syntaxhighlight>
{{out}}
<pre>
John (Male): Age 20
Jane (Female): Age 20
</pre>
=={{header|XLISP}}==
<langsyntaxhighlight lang="xlisp">(DEFINE-CLASS PROGRAMMING-LANGUAGE
(INSTANCE-VARIABLES NAME YEAR))
 
Line 4,203 ⟶ 4,620:
 
(DISPLAY (LISP 'DESCRIBE))
(NEWLINE)</langsyntaxhighlight>
{{out}}
<pre>(THE PROGRAMMING LANGUAGE LISP WAS CREATED IN 1958)</pre>
=={{header|zkl}}==
 
<syntaxhighlight lang="zkl">class C{ // define class named "C", no parents or attributes
println("starting construction"); // all code outside functions is wrapped into the constructor
var v; // instance data for this class
fcn init(x) // initializer for this class, calls constructor
{ v = x }
println("ending construction of ",self);
}
c1:=C(5); // create a new instance of C
c2:=c1("hoho"); // create another instance of C
println(C.v," ",c1.v," ",c2.v);</syntaxhighlight>
{{out}}
<pre>
starting construction
ending construction of Class(C)
starting construction
ending construction of Class(C)
Void 5 hoho
</pre>
<syntaxhighlight lang="zkl">C.__constructor(); // run base class constructor for giggles
C.init(456); // initialize base class without creating instance
println(C.v," ",c1.v);</syntaxhighlight>
{{out}}
<pre>
starting construction
ending construction of Class(C)
starting construction
ending construction of Class(C)
456 5
</pre>
=={{header|zonnon}}==
<langsyntaxhighlight lang="zonnon">
module Graphics;
type
Line 4,251 ⟶ 4,697:
writeln("Abs: ":4,p.Abs():3," Ord: ":5,p.Ord():3);
end Main.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,257 ⟶ 4,703:
Abs: 12 Ord: 12
</pre>
{{omit from|360 Assembly|not OO}}
=={{header|zkl}}==
{{omit from|6502 Assembly|not OO}}
<lang zkl>class C{ // define class named "C", no parents or attributes
{{omit from|8051 Assembly|not OO}}
println("starting construction"); // all code outside functions is wrapped into the constructor
{{omit from|8080 Assembly|not OO}}
var v; // instance data for this class
{{omit from|8086 Assembly|not OO}}
fcn init(x) // initializer for this class, calls constructor
{{omit from|68000 Assembly|not OO}}
{ v = x }
{{omit from|AArch64 Assembly|not OO}}
println("ending construction of ",self);
{{omit from|ARM Assembly|not OO}}
}
c1:=C(5); // create a new instance of C
c2:=c1("hoho"); // create another instance of C
println(C.v," ",c1.v," ",c2.v);</lang>
{{out}}
<pre>
starting construction
ending construction of Class(C)
starting construction
ending construction of Class(C)
Void 5 hoho
</pre>
<lang zkl>C.__constructor(); // run base class constructor for giggles
C.init(456); // initialize base class without creating instance
println(C.v," ",c1.v);</lang>
{{out}}
<pre>
starting construction
ending construction of Class(C)
starting construction
ending construction of Class(C)
456 5
</pre>
 
{{omit from|AWK|not OO}}
{{omit from|BASIC|not OO}}
Line 4,299 ⟶ 4,722:
{{omit from|Maxima}}
{{omit from|Metafont}}
{{omit from|MIPS Assembly|not OO}}
{{omit from|Modula-2}}
{{omit from|Octave}}
Line 4,307 ⟶ 4,731:
{{omit from|TI-89 BASIC}}
{{omit from|Vim Script}}
{{omit from|Z80 Assembly|not OO}}
{{omit from|ZX Spectrum Basic|not OO}}
9,476

edits