Classes: Difference between revisions
m
syntax highlighting fixup automation
(added MiniZinc example) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 39:
=={{header|11l}}==
<
Int public_variable // member variable = instance variable
. Int private_variable
Line 48:
F someMethod() // member function = method
.private_variable = 1
.public_variable = 10</
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:
<
F.virtual.new someMethod() -> N // this is polymorphic
print()</
=={{header|ActionScript}}==
<
public class MyClass {
Line 76:
}
}
}</
=={{header|Ada}}==
Line 82:
A package specification has the following form:
<
type My_Type is tagged private;
procedure Some_Procedure(Item : out My_Type);
Line 90:
Variable : Integer := -12;
end record;
end My_Package;</
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.
<
procedure Some_Procedure(Item : out My_Type) is
begin
Line 106:
return Temp;
end Set;
end My_Package;</
The Set function acts as a conversion constructor for My_Type.
An instance is typically created outside the package:
<
procedure Main is
Line 117:
Some_Procedure(Foo); -- Foo is doubled
Foo := Set(2007); -- Foo.Variable is set to 2007
end Main;</
=={{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.
<
var myvec = new Vector (x, y)
Line 127:
// draw the circle
}
}</
=={{header|ALGOL 68}}==
Line 141:
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]].
<
INT name1
);
Line 222:
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" #</
{{out}}
<pre>
Line 230:
=={{header|AmigaE}}==
<
varA, varP
ENDOBJECT
Line 256:
WriteF('\d\n', obj.getP())
END obj
ENDPROC</
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
AutoHotkey_L is prototype-based. However, for convenience, class-syntax may be used to create a base object.
<
obj.WhenCreated()
Line 279:
MsgBox, % "Object created at " this.time " on " this.date
}
}</
=={{header|BaCon}}==
Line 285:
This is an '''advanced feature''' to extend the the compiler we can also compile using g++ or clang++ using PRAGMA
<
PRAGMA COMPILER g++
PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive
Line 320:
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
<
PRAGMA COMPILER g++
PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive
Line 360:
PRINT "Book subject : ", Book1->subject FORMAT "%s%s\n"
PRINT "Book book_id : ", Book1->book_id FORMAT "%s%d\n"
</syntaxhighlight>
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<
DECLARE SUB MyClassSomeMethod (pthis AS MyClass)
DECLARE SUB MyClassInit (pthis AS MyClass)
Line 382:
SUB MyClassSomeMethod (pthis AS MyClass)
pthis.Variable = 1
END SUB</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
REM Declare the class:
Line 403:
REM Discard the instance:
PROC_discard(myclass{})</
=={{header|BQN}}==
Line 409:
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).
<
𝕊 value: # Constructor portion
priv ← value
Line 421:
obj.DispPriv@
obj.ChangePriv 6
obj.DispPriv@</
=={{header|blz}}==
<
# Constructors can take parameters (that automatically become properties)
constructor Ball(color, radius)
Line 441:
print(red_ball)
# => a red ball with radius 2
</syntaxhighlight>
=={{header|Bracmat}}==
Bracmat has no class-inheritance. Any object can function as a template for creating other objects.
<
= (x=)
(y=)
Line 452:
& new$(resolution,640,480):?VGA
& new$(resolution,1920,1080):?1080p
& out$("VGA: horizontal " !(VGA..x) " vertical " !(VGA..y)));</
{{out}}
<pre>VGA: horizontal 640 vertical 480</pre>
Line 458:
=={{header|C}}==
{{works with|gcc|4.0.2}}
<syntaxhighlight lang=c>
#include <stdlib.h>
Line 489:
MyClass obj = MyClass_new();
MyClass_someMethod(obj);
MyClass_delete(&obj);</
=={{header|C sharp|C#}}==
<
{
public MyClass()
Line 517:
System.Console.WriteLine( "Variable=" + instance.Variable.ToString() );
}
}</
=={{header|C++}}==
{{works with|g++|4.0.2}}
<
{
public:
Line 549:
MyClass* pInstance = new MyClass;
// Instances allocated with new must be explicitly destroyed when not needed any more:
delete pInstance;</
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 555:
Functions can also be defined inline:
<
{
public:
Line 562:
private:
int variable;
};</
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:
<
{
public:
virtual void someMethod(); // this is polymorphic
virtual ~MyClass(); // destructor
};</
=={{header|Clojure}}==
Line 577:
defrecord example:
<
; You can think of this as an interface
(defprotocol Foo (getFoo [this]))
Line 586:
; Create instance and invoke our method to return field value
(-> (Example1. "Hi") .getFoo)
"Hi"</
=={{header|COBOL}}==
<!-- This took far too long to create and to get to compile. -->
<
CLASS-ID. my-class INHERITS base.
Line 655:
.
END PROGRAM example-class-use.</
=={{header|Coco}}==
<
# The constructor is defined as a bare function. This
# constructor accepts one argument and automatically assigns it
Line 672:
# Instantiate the class using the 'new' operator.
rect = new Rectangle 2</
=={{header|CoffeeScript}}==
<
class Rectangle
# Constructor that accepts one argument
Line 688:
# Instantiate the class using the new operator
rect = new Rectangle 2</
=={{header|Common Lisp}}==
<
((radius :initarg :radius
:initform 1.0
Line 702:
> (defvar *c* (make-instance 'circle :radius 2))
> (area *c*)
12.566370614359172d0</
=={{header|Component Pascal}}==
Line 708:
Module that defines a Class
<
MODULE Point;
IMPORT
Line 750:
END ToString;
END Point.
</syntaxhighlight>
Module that uses previous class
<
MODULE DrivePoint;
IMPORT
Line 770:
END DrivePoint.
</syntaxhighlight>
Execute: ^Q DrivePoint.Do<br/>
{{out}}
Line 781:
=={{header|Crystal}}==
{{trans|Ruby}}
<
def initialize
Line 794:
my_class = MyClass.new
</syntaxhighlight>
=={{header|D}}==
<
class MyClass {
Line 839:
// prints 'variable = 99'
writeln("variable = ", obj.variable);
}</
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 885:
lMyClass.Free;
end;
end.</
=={{header|DM}}==
Line 891:
Adding elements (procs, variables, classes) to this tree is done by defining the name and such.
<syntaxhighlight lang
This declares a type "/s" at the root of the tree, which can now be instantiated.
Line 897:
A more complicated example:
<syntaxhighlight lang=DM>
// Declare the class "/foo"
foo
Line 920:
x.bar = 10 // Assign to the instance variable.
x.baz() // Call "baz" on our instance.
</syntaxhighlight>
This is enough to declare a
=={{header|Dragon}}==
<
func val(){
showln 10+20
}
}
</syntaxhighlight>
=={{header|DWScript}}==
Methods can be implemented inline or out-of-line, this sample illustrates both.
<
TMyClass = class
private
Line 958:
lMyClass.SomeField := 99;
lMyClass.SomeMethod;</
=={{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.
<
def color {
to colorize(thing :String) {
Line 970:
}
return color
}</
Example interactive session creating and using it:
<
# value: <color>
? red.colorize("apple")
# value: "red apple"</
=={{header|EchoLisp}}==
<
(lib 'gloops) ; load oo library
Line 994:
(lambda (p w) (printf " From %a (age %d). Dear writer of %a ..." p p.age w.books )))
</syntaxhighlight>
{{Output}}
<
;; instantiate
(define simone (make-instance Person :name 'simone :age 42)) ;; slots values by name
Line 1,013:
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.
<
class MY_CLASS
end
</syntaxhighlight>
=== Add a Creation Procedure (Constructor) ===
<
class MY_CLASS
Line 1,039:
end
</syntaxhighlight>
=== Add Multiple Creation Procedures (Constructors) ===
In Eiffel, you may have more than one creation procedure (or "Constructor").
<
class MY_CLASS
Line 1,086:
end
</syntaxhighlight>
=== 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".
<
class MY_CLASS
Line 1,139:
end
</syntaxhighlight>
=={{header|Elena}}==
ELENA 4.x :
<
class MyClass
Line 1,169:
// get the variable
console.printLine("Variable=",instance.Variable)
}</
=={{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:
<
CLASS QUADRATO
Line 1,203:
PRINT(PERIMETROQ)
END PROGRAM
</syntaxhighlight>
The answers is
100
Line 1,210:
=={{header|F_Sharp|F#}}==
A minimal example as required by the task description:
<
let mutable var = init // a private instance variable
member x.Method() = // a simple method
Line 1,218:
// create an instance and use it
let myObject = new MyClass(42)
myObject.Method()</
A somewhat more meaningful example, inspired by the Haskell version:
<
type Shape =
Line 1,235:
interface Shape with
member x.Perimeter() = 2.0 * width + 2.0 * height
member x.Area() = width * height</
=={{header|Factor}}==
<
M: my-class quux foo>> 20 + ;
C: <my-class> my-class
Line 1,245:
C: <my-child-class> my-child-class
M: my-child-class foobar 20 >>quux ;
20 20 30 <my-child-class> foobar quux ! result: 30</
=={{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.
<
[ static block ]
[ properties declaration ]
[init block]
[method list]
end</
Example of a class:
<
capacity = max_msg * 10
Line 1,270:
end
end</
Instantiation:
<
// Ouputs: Box now ready for 100 messages.</
=={{header|Fancy}}==
<
read_slot: 'instance_var # creates getter method for @instance_var
@@class_var = []
Line 1,302:
}
myclass = MyClass new</
=={{header|Fantom}}==
<
{
// an instance variable
Line 1,331:
c := MyClass { x = 3 } // instantiates the class, sets x to 3
}
}</
=={{header|Forth}}==
Line 1,339:
Declare a class
<
int memvar
Line 1,352:
:m show: ( -- ) ." Memvar = " memvar . ;m
;class</
Allocate a static object
<syntaxhighlight lang
Allocate a dynamic object, saving its pointer in a global variable.
<syntaxhighlight lang
Call member functions
<
show: newInstance</
Free a dynamically allocated object
<
0 to newInstance \ no dangling pointers!</
Example of dynamic allocation and local variable use"
<
New> MyClass to obj
show: obj
1000 set: obj
obj dispose ;</
Line 1,382:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<
:class foo \ begin class foo definition
Line 1,413:
bar \ 10 30
bar' \ 10 30
</syntaxhighlight>
=={{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
<
!-----------------------------------------------------------------------
!Module accuracy defines precision and some constants
Line 1,598:
end program rosetta_class
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
Type MyClass
Line 1,627:
Print mc.MyInt, mc.Treble()
Print "Press any key to quit the program"
Sleep</
{{out}}
Line 1,636:
=={{header|GLSL}}==
There are no classes in GLSL, but they can be simulated using structs:
<
struct Rectangle{
float width;
Line 1,656:
return (self.width+self.height)*2.0;
}
</syntaxhighlight>
=={{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.
<
import "fmt"
Line 1,709:
fmt.Println(forTwo)
fmt.Println(forToo)
}</
{{out}}
<pre>
Line 1,732:
This happens when a method is called through an interface. Consider this code in addition to the example above.
<
type happinessTester interface {
Line 1,757:
ps.happy())
}
}</
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,778:
=={{header|Groovy}}==
A class:
<
class Stuff {
/** Heare bee anne instance variable declared */
Line 1,792:
println "This stuff is flangulating its guts: ${guts}"
}
}</
A demonstration:
<
I have made mistakes in the past.
I have made mistakes in the future.
Line 1,810:
'''
stuff.flangulate()</
{{out}}
Line 1,828:
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).
<
perimeter :: a -> Double
area :: a -> Double
Line 1,860:
{- The correct version of apRatio (and hence the correct
implementations of perimeter and area) is chosen based on the type
of the argument. -}</
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.
<
{- This Shape is a type rather than a type class. Rectangle and
Circle are its constructors. -}
Line 1,886:
{- 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. -}</
== Icon and {{header|Unicon}} ==
Unicon supports classes.
<
# method definition
Line 1,910:
write (x2.x)
write (x2.double ()) # call a method
end</
=={{header|J}}==
'''Class definition:'''
<
exampleMethod=: monad define
Line 1,924:
)
exampleInstanceVariable=: 0</
'''Instantiation:'''
<
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}}==
<
// instance variable
Line 1,950:
this.variable = 1;
}
}</
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
=={{header|JavaScript}}==
Line 1,958:
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:
<
function Car(brand, weight) {
this.brand = brand;
Line 1,981:
alert(cars[i].brand + " " + cars[i].weight + " " + cars[i].size + ", " +
(cars[i] instanceof Car) + " " + (cars[i] instanceof Truck));
}</
The alerts shows us:
<pre>
Line 1,990:
===ES6===
<
/**
* A few brands of cars
Line 2,066:
let myTruck = new Truck('Volvo', 2);
console.log(myTruck.formattedStats);
myTruck.drive(40);</
Output:
Line 2,081:
Multiple dispatch is a core feature of the language.
<
habitat(::Mammal) = "planet Earth"
Line 2,100:
for a in arr
println("Habitat of $a: ", habitat(a))
end</
{{output}}
Line 2,108:
=={{header|Kotlin}}==
<
fun treble(): Int = myInt * 3
}
Line 2,115:
val mc = MyClass(24)
print("${mc.myInt}, ${mc.treble()}")
}</
{{out}}
Line 2,125:
In Lasso, a "class" is termed a "type"
<
define mytype => type {
data
Line 2,144:
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"'</
=={{header|LFE}}==
<
(defmodule simple-object
(export all))
Line 2,180:
"Get a variable passed when constructing the object."
(funcall (get-method object 'species) object))
</syntaxhighlight>
Usage from the LFE REPL:
<
> (slurp '"simple-object.lfe")
#(ok simple-object)
Line 2,192:
> (get-species my-fish)
"Carp"
</syntaxhighlight>
=={{header|Lingo}}==
'''Class definition:'''
<
-- @desc Class "MyClass"
-- @file parent script "MyClass"
Line 2,214:
me._myvar = me._myvar * 2
put me._myvar
end</
'''Instantiation:'''
<
foo.doubleAndPrint()
-- 46</
=={{header|Lisaac}}==
<
+ name := SAMPLE;
Line 2,245:
sample := SAMPLE.clone;
sample.some_method;
);</
=={{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.
<
instantiates(metaclass)).
Line 2,268:
:- private(state/1).
:- end_object.</
A simple usage example after compiling and loading the above code:
<
Instance = o1
yes
Line 2,276:
| ?- o1::method(Value).
Value = 1
yes</
=={{header|Lua}}==
Classes in Lua are implemented with metatables. This doesn't implement a full system, but it gets the basic idea:
<
__index = function(z,i) return myclass[i] end, --this makes class variables a possibility
setvar = function(z, n) z.var = n end
Line 2,293:
instance:setvar(6)
print(instance.var) -->6</
=={{header|M2000 Interpreter}}==
<
Class zz {
module bb {
Line 2,500:
Print pr2=>toString$()
</syntaxhighlight>
=={{header|MATLAB}}==
Line 2,510:
GenericClass.m: Class Constructor
<
if isempty(varargin) %No input arguments
Line 2,521:
GenericClassInstance = class(GenericClassInstance,'GenericClass');
end</
getValue.m:
<
function value = getValue(GenericClassInstance)
value = GenericClassInstance.classVariable;
end</
setValue.m:
<
function GenericClassInstance = setValue(GenericClassInstance,newValue)
GenericClassInstance.classVariable = newValue;
end</
display.m: This method overloads the "disp()" command
<
disp(sprintf('%f',GenericClassInstance.classVariable));
end</
Sample Usage:
<
3.000000
>> myClass = setValue(myClass,pi)
Line 2,546:
ans =
3.141592653589793</
@GenericClass2
GenericClass2.m: This is the classdef, it includes the class constructor as well as class variables and methods.
<
properties
Line 2,577:
end %methods
end</
getValue.m:
<
function value = getValue(GenericClassInstance)
value = GenericClassInstance.classVariable;
end</
display.m: This method overloads the "disp()" command
<
disp(sprintf('%f',GenericClassInstance.classVariable));
end</
Sample Usage:
<
3.000000
>> setValue(myClass,pi)
Line 2,596:
ans =
3.141592653589793</
=={{header|MiniScript}}==
<
Weapon = { "name": "Sword", "damage": 3 }
Weapon.slice = function()
Line 2,609:
wep.name = "Lance"
wep.slice</
=={{header|MiniZinc}}==
MiniZinc does not have classes, but they can be simulated using functions with constraints:
<
var int: Rectangle(var int: width, var int: height) =
let {
Line 2,640:
% print the area of the rectangle
output [show(area1),"\n"];</
=={{header|Nanoquery}}==
<
declare name
Line 2,659:
// display the name value
println inst.getName()</
=={{header|Nemerle}}==
<
{
public this() { } // the constructor in Nemerle is always named 'this'
Line 2,680:
def myInstance = MyClass(); // no 'new' keyword needed
myInstance.MyVariable = 42; // set MyVariable
System.Console.WriteLine($"My variable is $(myInstance.MyVariable)") // get MyVariable</
=={{header|NetRexx}}==
<
properties private -- class scope
Line 2,713:
method test(s=boolean)
mies = 3
say s mies</
=={{header|Nim}}==
{{trans|Python}}
<
name: int
Line 2,743:
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</
=={{header|Oberon-2}}==
{{works with|OO2C|2.1.11}}
<
TYPE
Line 2,768:
END Increment;
END M.</
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}}==
<
class MyClass {
@var : Int;
Line 2,805:
}
}
}</
=={{header|Object Pascal}}==
Line 2,811:
:''Note: This is not part of standard Pascal, but Turbo Pascal specific''
<
MyClass = object
variable: integer;
Line 2,845:
instance.done;
dispose(pInstance, done);
end;</
=={{header|Objective-C}}==
Line 2,852:
{{works with|GNUstep}}
Interface:
<
static int myClassVariable = 0;
Line 2,862:
- (int)variable; // Typical accessor - you should use the same name as the variable
@end</
Implementation:
<
// Was not declared because init is defined in NSObject
Line 2,882:
}
@end</
Using the class:
<
MyClass *mc = [[MyClass alloc] init];
// Sending a message
[mc variable];</
=={{header|OCaml}}==
<
object (self)
val mutable variable = 0
method some_method = variable <- 1
end</
Using the class:
Line 2,909:
=={{header|Oforth}}==
Class creation
<
MyClass method: initialize(v) v := att ;</
Usage : instantiation
<syntaxhighlight lang
=={{header|Ol}}==
Line 2,922:
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.
<
c = .circle~new
Line 2,950:
::method print
expose radius
say "A circle of radius" radius "centered at location ("||self~x","self~y")"</
=={{header|OxygenBasic}}==
<
Class MyObject
Line 2,984:
del v
</syntaxhighlight>
=={{header|Oz}}==
Classes are created at runtime and first-class values.
<
class Something
feat
Line 3,011:
%% call a method
{Object increase}</
=={{header|Pascal}}==
Line 3,019:
{{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:
<
# a class is a package (i.e. a namespace) with methods in it
package MyClass;
Line 3,037:
$self->{variable} = 1;
}
}</
This is the same using the [http://search.cpan.org/perldoc?Moose Moose] object system:
<
package MyClass;
use Moose;
Line 3,051:
$self->variable(1);
}
}</
This is the same class using the [http://search.cpan.org/perldoc?MooseX::Declare MooseX::Declare] extention:
<
class MyClass {
has 'variable' => (is => 'rw', default => 0);
Line 3,060:
$self->variable(1);
}
}</
All of the above classes can be used the same way:
<
$instance->some_method; # invoke method on object instance
# instance deallocates when the last reference falls out of scope</
=={{header|Phix}}==
{{libheader|Phix/Class}}
<!--<
<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>
<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>
Line 3,099:
<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>
<!--</
{{out}}
<pre>
Line 3,111:
=={{header|PHL}}==
<
extern printf;
Line 3,133:
printf("obj.myField: %i\n", obj::get_myField);
return 0;
]</
=={{header|PHP}}==
<
public static $classVar;
public $instanceVar; // can also initialize it here
Line 3,147:
}
}
$myObj = new MyClass();</
<!-- TODO ;; 2008-01-24 07:35 fill this in when i get a few spare moments
/*
Line 3,169:
=={{header|PicoLisp}}==
<
# dx dy
Line 3,176:
(println # Create a rectangle, and print its area
(area> (new '(+Rectangle) 'dx 3 'dy 4)) )</
=={{header|Pop11}}==
Object system is implemented as a library, so we must first load it.
<
define :class MyClass;
slot value = 1;
enddefine;</
Defining class MyClass automatically defines two constructors, newMyClass and consMyClass and slot (instance variable) accessors, so we can immediately start using our new class:
<
lvars instance1 = newMyClass();
;;; Construct instance with explicitely given slot values
Line 3,199:
12 -> value(instance1);
;;; Print it
value(instance1) =></
We can add methods at any time (even after creating an instance):
<
0 -> value(x);
enddefine;
reset(instance1);
;;; Print it
instance1 =></
=={{header|Portugol}}==
{{trans|D}}
<
programa {
inclua biblioteca Objetos --> obj
Line 3,255:
}
</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.
<
Add-Type -Language CSharp -TypeDefinition @'
public class MyClass
Line 3,289:
}
'@
</syntaxhighlight>
{{works with|PowerShell|5}}
<br>
<b>Basic syntax</b>
<
class MyClass
{
Line 3,311:
}
}
</syntaxhighlight>
<b>Example class</b>
<
class Banana
{
Line 3,347:
}
}
</syntaxhighlight>
<b>Using the example class</b>
<
$MyBanana = [banana]::New()
$YourBanana = [banana]::New( $True )
Line 3,355:
If ( -not $MyBanana.IsReadyToEat() -and $YourBanana.IsReadyToEat() )
{ $MySecondBanana = $YourBanana }
</syntaxhighlight>
=={{header|Processing}}==
<
{
// instance variable:
Line 3,374:
// the method has no argument or local variable called "name", so we can omit the "this"
}
}</
How to use it:
<
ProgrammingLanguage processing = new ProgrammingLanguage("Processing");
// call the method:
processing.sayHello();</
{{out}}
<pre>Hello from the programming language Processing</pre>
Line 3,386:
=={{header|PureBasic}}==
===Generic version===
<
Get.i()
Set(Value.i)
Line 3,441:
*Foo\Set(341)
MessageRequester("Info", "Foo = " + *Foo\ToString() )
*Foo\Destroy()</
===Simple OOP Version===
Using the open-source precompiler [http://www.development-lounge.de/viewtopic.php?t=5915 SimpleOOP].
<
Private Value.i
Line 3,474:
*Demo.foo = NewObject.foo()
*Demo\Set(4)
MessageRequester("Info", "Val= " + *Demo\ToString())</
=={{header|Python}}==
<
name2 = 2 # Class attribute
Line 3,514:
print person1.age # Raises AttributeError exception!
person2 = MyOtherClass("Jane", "Female", 23)
print person2.name, person2.gender, person2.age # "Jane Female 23"</
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,520:
New-style classes inherit from "object" or any descendant of the "object" class:
<
...</
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).
Line 3,530:
===S3===
S3 provides a very simple class system designed to be easily used interactively.
<
circS3 <- list(radius=5.5, centre=c(3, 4.2))
class(circS3) <- "circle"
Line 3,542:
type="l", ...)
}
plot(circS3)</
===S4===
S4 is a more formal class system that provides validity checking and a way to define different methods for different input signatures.
<
representation(
radius="numeric",
Line 3,569:
type="l", ...)
})
plot(circS4)</
=={{header|Racket}}==
Line 3,575:
Racket programs heavily use functions, but classes and objects are available as well:
<
#lang racket
Line 3,591:
;; constructing an instance
(new fish% [size 50])
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang=raku
my Camel $a .= new;
Line 3,602:
my Camel $b .= new: humps => 2;
say $b.humps;</
A more complex example:
<syntaxhighlight lang=raku
has Int $!age; # With the ! twigil, no public accessor method is generated
has Str $.name;
Line 3,631:
my Butterfly $b .= new(name => 'Osgood', age => 4);
say "Name: {$b.name}, Color: {$b.color}";
$b.flap;</
=={{header|RapidQ}}==
<
Variable AS INTEGER
Line 3,650:
' invoke the method
instance.someMethod</
=={{header|Raven}}==
Build classes:
<
'I am Alpha.' as greeting
define say_hello
Line 3,660:
class Beta extend Alpha
'I am Beta!' as greeting</
Execute classes to create objects:
<
Beta as beta</
Call methods:
<
beta.say_hello</
Result:
<
I am Beta!</
=={{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>
Class NumberContainer
Private TheNumber As Integer
Line 3,692:
End Sub
End Class
</syntaxhighlight>
<syntaxhighlight lang=vb>
Dim num As New NumberContainer(1) ' call the constructor
num.Number = num.Number + 5 ' call both Number methods
</syntaxhighlight>
=={{header|REBOL}}==
<
Title: "Classes"
URL: http://rosettacode.org/wiki/Classes
Line 3,738:
print "Howdy, Pecos!" pecos/hi
print "Tell us about yourself?" pecos/boast</
{{out}}
Line 3,756:
Simple program to define class and create an object
<
New point { x=10 y=20 z=30 print() }
Class Point x y z func print see x + nl + y + nl + z + nl
</syntaxhighlight>
The previous program can be written in another way
<
New point # create new object using the point class
{ # access the new object attributes and methods
Line 3,779:
y + nl + # print the y attribute
z + nl # print the z attribute
</syntaxhighlight>
=={{header|Ruby}}==
<
def initialize
Line 3,795:
my_class = MyClass.new #allocates an object and calls it's initialize method, then returns it.
</syntaxhighlight>
=={{header|Rust}}==
<
struct MyClass {
variable: i32, // member variable = instance variable
Line 3,829:
// Both instances are automatically deleted when their scope ends.
}
</syntaxhighlight>
=={{header|Sather}}==
<
readonly attr x:INT; -- give a public getter, not a setter
private attr y:INT; -- no getter, no setter
Line 3,852:
return y + s;
end;
end;</
<
main is
test ::= #CLASSTEST(1, 2, 3);
Line 3,865:
#OUT + test.getPrivateY(0) + "\n";
end;
end;</
=={{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.
<
* creates "val variable1: Int" with that value.
*/
Line 3,892:
println(m.myMethod) // prints 0
println(n.myMethod) // prints 3
}</
=={{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]
<
(if (>= balance amount)
(begin (set! balance (- balance amount))
Line 3,909:
(else (error "Unknown request -- MAKE-ACCOUNT"
m))))
dispatch)</
=={{header|Sidef}}==
<
method add(num) {
instance_var += num;
Line 3,920:
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</
=={{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.
<
CLASS MyClass(instanceVariable);
INTEGER instanceVariable;
Line 3,942:
myObject :- NEW MyClass(5);
myObject.doMyMethod(2)
END</
{{out}}
<pre> 5 + 2 = 7</pre>
Line 3,948:
=={{header|Slate}}==
Slate objects operate as prototypes with multi-methods:
<
MyPrototype traits addSlot: #classVar.
Line 3,959:
[
x instanceVar = 1 /\ (x classVar = 3)
].</
=={{header|Smalltalk}}==
<
instanceVariableNames: 'instanceVar'
classVariableNames: 'classVar'
Line 3,976:
^self instanceVar = 1; classVar = 3 ! !
MyClass new someMethod!</
=={{header|SuperCollider}}==
<
Line 4,015:
</syntaxhighlight>
Call it:
<
SpecialObject.randomizeAll;
a = SpecialObject(8);
a.coordinates;
</syntaxhighlight>
=={{header|Swift}}==
<
// stored property
Line 4,044:
self.variable = 1
}
}</
Instantiate this class using:
<syntaxhighlight lang
=={{header|Tcl}}==
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<
oo::class create summation {
variable v
Line 4,071:
puts "Add $i to get [$sum add $i]"
}
$sum destroy</
=={{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.
<
{
//Constructor function.
Line 4,110:
stdout.printf("#%d %s $%d %v %v, %v %v", i, car.brand, car.price, car.weight, car.size,
car instanceof Car, car instanceof Truck);
}</
{{out}} from console :
<pre>
Line 4,118:
=={{header|Transd}}==
<
class Point : {
Line 4,141:
(for p in v do (print p))
) )
}</
{{out}}
<pre>
Line 4,150:
=={{header|TXR}}==
<
cached-area
Line 4,173:
(:method calc-area (self)
(* self.length self.length)))</
{{out}}
Line 4,199:
{{works with|ksh93}}
ksh93 has "type variables" which essentially declares a class.
<
integer sum
Line 4,217:
s.add $i
done
print ${s.sum}</
=={{header|Vala}}==
<
// Instance variable
public int variable;
Line 4,242:
instance.variable = 84;
print("%d\n", instance.variable);
}</
=={{header|VBA}}==
Line 4,254:
This is the contents of a class module "Foo" (like in the Visual Basic .NET example below):
<
Private m_bar As Integer
Line 4,284:
'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</
===Using an object===
Objects (e.g. of class Foo) are created and used in "normal" modules.
<
'declare and create separately
Dim f As Foo
Line 4,324:
'this will trigger one or two "object destroyed" messages
'depending on whether f0 was created...
End Sub</
{{out}}
Line 4,339:
=={{header|Visual Basic .NET}}==
===Defining a class===
<
Private m_Bar As Integer
Line 4,367:
End Function
End Class</
===Using an object===
<
Dim foo1 As Foo
foo1 = New Foo
Line 4,391:
'Reading/writing properties
Console.WriteLine(foo4.Bar)
foo4.Bar = 1000</
=={{header|Visual FoxPro}}==
Visual FoxPro has a large number of base classes - Session is one of them.
<
LOCAL o1 As MyClass, o2 As MyClass
*!* Instantiate o1
Line 4,424:
ENDPROC
ENDDEFINE
</syntaxhighlight>
{{out}}
<pre>
Line 4,432:
=={{header|Wren}}==
<
// Constructs a Bear instance passing it a name
// which is stored in the field _name
Line 4,452:
System.print("The bear is called %(b.name).")
// Make a noise.
b.makeNoise()</
{{out}}
Line 4,463:
===UASM 2.52===
Details about the UASM class extention can be found [http://www.terraspace.co.uk/uasm252_ext.pdf here].
<
option casemap:none
Line 4,537:
end
</syntaxhighlight>
{{out}}
<pre>
Line 4,544:
=={{header|XBS}}==
<
construct=func(self,Name,Age,Gender){
self:Name=Name;
Line 4,558:
log(John::ToString());
set Jane = new Person with ["Jane",20,"Female"]
log(Jane::ToString());</
{{out}}
<pre>
Line 4,566:
=={{header|XLISP}}==
<
(INSTANCE-VARIABLES NAME YEAR))
Line 4,584:
(DISPLAY (LISP 'DESCRIBE))
(NEWLINE)</
{{out}}
<pre>(THE PROGRAMMING LANGUAGE LISP WAS CREATED IN 1958)</pre>
=={{header|zkl}}==
<
println("starting construction"); // all code outside functions is wrapped into the constructor
var v; // instance data for this class
Line 4,598:
c1:=C(5); // create a new instance of C
c2:=c1("hoho"); // create another instance of C
println(C.v," ",c1.v," ",c2.v);</
{{out}}
<pre>
Line 4,607:
Void 5 hoho
</pre>
<
C.init(456); // initialize base class without creating instance
println(C.v," ",c1.v);</
{{out}}
<pre>
Line 4,650:
=={{header|zonnon}}==
<
module Graphics;
type
Line 4,693:
writeln("Abs: ":4,p.Abs():3," Ord: ":5,p.Ord():3);
end Main.
</syntaxhighlight>
{{out}}
<pre>
|