Call an object method: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(40 intermediate revisions by 25 users not shown)
Line 1: Line 1:
{{task|Basic language learning}}
[[Category:Object oriented]]
[[Category:Object oriented]]
[[Category:Encyclopedia]]
[[Category:Encyclopedia]]
{{task|Basic language learning}}


In [[object-oriented programming]] a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
In [[object-oriented programming]] a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.


Show how to call a static or class method, and an instance method of a class.
Show how to call a static or class method, and an instance method of a class.

=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang actionscript>// Static
<syntaxhighlight lang="actionscript">// Static
MyClass.method(someParameter);
MyClass.method(someParameter);


// Instance
// Instance
myInstance.method(someParameter);</lang>
myInstance.method(someParameter);</syntaxhighlight>

=={{header|Ada}}==
=={{header|Ada}}==
Ada is a language based on strict typing. Nevertheless, since Ada 95 (the first major revision of the language), Ada also includes the concepts of a class. Types may be tagged, and for each tagged type T there is an associated type T'Class. If you define a method as "procedure Primitive(Self: T)", the actual parameter Self must be of type T, exactly, and the method Primitive will be called, well, statically. This may be surprising, if you are used to other object-oriented languages.
Ada is a language based on strict typing. Nevertheless, since Ada 95 (the first major revision of the language), Ada also includes the concepts of a class. Types may be tagged, and for each tagged type T there is an associated type T'Class. If you define a method as "procedure Primitive(Self: T)", the actual parameter Self must be of type T, exactly, and the method Primitive will be called, well, statically. This may be surprising, if you are used to other object-oriented languages.
Line 22: Line 20:


Specify the class My_Class, with one primitive subprogram, one dynamic subprogram and a static subprogram:
Specify the class My_Class, with one primitive subprogram, one dynamic subprogram and a static subprogram:
<lang Ada> package My_Class is
<syntaxhighlight lang="ada"> package My_Class is
type Object is tagged private;
type Object is tagged private;
procedure Primitive(Self: Object); -- primitive subprogram
procedure Primitive(Self: Object); -- primitive subprogram
Line 29: Line 27:
private
private
type Object is tagged null record;
type Object is tagged null record;
end My_Class;</lang>
end My_Class;</syntaxhighlight>


Implement the package:
Implement the package:
<lang Ada> package body My_Class is
<syntaxhighlight lang="ada"> package body My_Class is
procedure Primitive(Self: Object) is
procedure Primitive(Self: Object) is
begin
begin
Line 49: Line 47:
Put_Line("Greetings");
Put_Line("Greetings");
end Static;
end Static;
end My_Class;</lang>
end My_Class;</syntaxhighlight>


Specify and implement a subclass of My_Class:
Specify and implement a subclass of My_Class:
<lang Ada> package Other_Class is
<syntaxhighlight lang="ada"> package Other_Class is
type Object is new My_Class.Object with null record;
type Object is new My_Class.Object with null record;
overriding procedure Primitive(Self: Object);
overriding procedure Primitive(Self: Object);
Line 62: Line 60:
Put_Line("Hello Universe!");
Put_Line("Hello Universe!");
end Primitive;
end Primitive;
end Other_Class;</lang>
end Other_Class;</syntaxhighlight>


The main program, making the dynamic and static calls:
The main program, making the dynamic and static calls:


<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;


procedure Call_Method is
procedure Call_Method is
Line 85: Line 83:
Ob1.Dynamic;
Ob1.Dynamic;
Ob2.Dynamic;
Ob2.Dynamic;
end Call_Method;</lang>
end Call_Method;</syntaxhighlight>


{{out}}
{{out}}
Line 94: Line 92:
Hi there! ... Hello World!
Hi there! ... Hello World!
Hi there! ... Hello Universe!</pre>
Hi there! ... Hello Universe!</pre>
=={{header|ALGOL 68}}==
Algol 68 doesn't do OO as such, but it has structures, the members of which can be procedures. This allows OO features to be implemented, though without syntactic sugar, "this" pointers must be passed explicitly. In Algol 68, <code>a OF b</code> is used where most other languages would use <code>b.a</code>.
<br>
This means that a call to an instance method called "print" say of a class instance "a" in Algol 68 would be written <code>( print OF a )( a )</code>, - note the explicit "this" parameter - whereas <code>a.print</code> would be used in most other languages.
<br>
Class methods could be members of the structure (as here) without a "this" parameter, or could be procedures defined outside the structure.
<br>
In this example, the instance and class methods return VOID, but this is not necessary, any return type could be used.
<syntaxhighlight lang="algol68">
BEGIN # demonstrate a possible method of simulating class & instance methods #
# declare a "class" #
MODE ANIMAL = STRUCT( STRING species
, PROC( REF ANIMAL )VOID print # instance method #
, PROC VOID cm # class method #
);
# constructor #
PROC new animal = ( STRING species )REF REF ANIMAL:
BEGIN
HEAP ANIMAL newv := ANIMAL( species
, ( REF ANIMAL this )VOID:
print( ( "[animal instance[", species OF this, "]]" ) )
, VOID: print( ( "[animal class method called]" ) )
);
HEAP REF ANIMAL newa := newv;
newa
END # new animal # ;

REF ANIMAL a
:= new animal( "PANTHERA TIGRIS" ); # create an instance of ANIMAL #
cm OF a; # call the class method #
( print OF a )( a ) # call the instance method #
END
</syntaxhighlight>
{{out}}
<pre>
[animal class method called][animal instance[PANTHERA TIGRIS]]
</pre>


=={{header|Apex}}==
=={{header|Apex}}==
<lang Java>// Static
<syntaxhighlight lang="java">// Static
MyClass.method(someParameter);
MyClass.method(someParameter);


// Instance
// Instance
myInstance.method(someParameter);</lang>
myInstance.method(someParameter);</syntaxhighlight>

=={{header|Arturo}}==

<lang arturo>Person #{
name ""
surname ""

init [n,s]{
name n
surname s
}

sayHello {
print "Hello " + name + "!"
}
}

person $(new ~Person "John" "Doe")
person.sayHello
</lang>

{{out}}

<pre>Hello John!</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
{{works with|AutoHotkey_L}}
(AutoHotkey Basic does not have classes)
(AutoHotkey Basic does not have classes)
<lang AHK>class myClass
<syntaxhighlight lang="ahk">class myClass
{
{
Method(someParameter){
Method(someParameter){
Line 138: Line 149:
myClass.method("hi")
myClass.method("hi")
myInstance := new myClass
myInstance := new myClass
myInstance.Method("bye")</lang>
myInstance.Method("bye")</syntaxhighlight>

=={{header|Bracmat}}==
=={{header|Bracmat}}==
Bracmat has no classes. Rather, objects can be created as copies of other objects. In the example below, the variable <code>MyObject</code> has a copy of variable <code>MyClass</code> as value. Notice the extra level of reference in <code>(MyObject..Method)$argument</code>, comparable to <code>MyObject->Method(argument)</code> in C. Rather than being the object itself, <code>MyObject</code> points to an object and can be aliased by assigning to another variable.
Bracmat has no classes. Rather, objects can be created as copies of other objects. In the example below, the variable <code>MyObject</code> has a copy of variable <code>MyClass</code> as value. Notice the extra level of reference in <code>(MyObject..Method)$argument</code>, comparable to <code>MyObject->Method(argument)</code> in C. Rather than being the object itself, <code>MyObject</code> points to an object and can be aliased by assigning to another variable.


Inside an object, the object is represented by <code>its</code>, comparable to <code>this</code> in other languages.
Inside an object, the object is represented by <code>its</code>, comparable to <code>this</code> in other languages.
<lang bracmat>( ( myClass
<syntaxhighlight lang="bracmat">( ( myClass
= (name=aClass)
= (name=aClass)
( Method
( Method
Line 156: Line 166:
& !MyObject:?Alias
& !MyObject:?Alias
& (Alias..Method)$"Example of calling an instance method from an alias"
& (Alias..Method)$"Example of calling an instance method from an alias"
);</lang>
);</syntaxhighlight>
Output:
Output:
<pre>Output from aClass: Example of calling a 'class' method
<pre>Output from aClass: Example of calling a 'class' method
Line 162: Line 172:
Output from object1: Example of calling an instance method from an alias</pre>
Output from object1: Example of calling an instance method from an alias</pre>



=={{header|ChucK}}==
<lang>
MyClass myClassObject;
myClassObject.myFunction(some parameter);
</lang>
=={{header|C}}==
=={{header|C}}==
C has structures and it also has function pointers, which allows C structures to be associated with any function with the same signature as the pointer. Thus, C structures can also have object methods.
C has structures and it also has function pointers, which allows C structures to be associated with any function with the same signature as the pointer. Thus, C structures can also have object methods.
<syntaxhighlight lang="c">
<lang C>
#include<stdlib.h>
#include<stdlib.h>
#include<stdio.h>
#include<stdio.h>
Line 197: Line 203:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
And yes, it works :
And yes, it works :
<pre>
<pre>
Line 205: Line 211:
</pre>
</pre>
=={{header|C++}}==
=={{header|C++}}==
<lang cpp>// Static
<syntaxhighlight lang="cpp">// Static
MyClass::method(someParameter);
MyClass::method(someParameter);


Line 213: Line 219:
// Pointer
// Pointer
MyPointer->method(someParameter);
MyPointer->method(someParameter);
</syntaxhighlight>
</lang>

=={{header|C_sharp|C#}}==
=={{header|C_sharp|C#}}==
<lang csharp>// Static
<syntaxhighlight lang="csharp">// Static
MyClass.Method(someParameter);
MyClass.Method(someParameter);
// Instance
// Instance
myInstance.Method(someParameter);</lang>
myInstance.Method(someParameter);</syntaxhighlight>
=={{header|ChucK}}==

<syntaxhighlight lang="c">
MyClass myClassObject;
myClassObject.myFunction(some parameter);
</syntaxhighlight>
=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(Long/toHexString 15) ; use forward slash for static methods
<syntaxhighlight lang="clojure">(Long/toHexString 15) ; use forward slash for static methods
(System/currentTimeMillis)
(System/currentTimeMillis)


(.equals 1 2) ; use dot operator to call instance methods
(.equals 1 2) ; use dot operator to call instance methods
(. 1 (equals 2)) ; alternative style</lang>
(. 1 (equals 2)) ; alternative style</syntaxhighlight>

=={{header|COBOL}}==
=={{header|COBOL}}==
{{Works with|COBOL 2002}}
COBOL has two ways to invoke a method: the <code>INVOKE</code> statement and inline method invocation.
There are two ways to invoke a method: the <code>INVOKE</code> statement and inline method invocation.
<lang cobol>*> INVOKE
<syntaxhighlight lang="cobolfree">*> INVOKE statements.
INVOKE FooClass "someMethod" RETURNING bar *> Factory object
INVOKE foo-instance "anotherMethod" RETURNING bar *> Instance object
INVOKE my-class "some-method" *> Factory object
USING BY REFERENCE some-parameter
RETURNING foo
INVOKE my-instance "another-method" *> Instance object
USING BY REFERENCE some-parameter
RETURNING foo


*> Inline method invocation
*> Inline method invocation.
MOVE FooClass::"someMethod" TO bar *> Factory object
MOVE my-class::"some-method"(some-parameter) TO foo *> Factory object
MOVE foo-instance::"anotherMethod" TO bar *> Instance object</lang>
MOVE my-instance::"another-method"(some-parameter) TO foo *> Instance object</syntaxhighlight>


To call factory methods of objects of an unknown type (such as when you may have a subclass of the class wanted), it is necessary to get a reference to the class's factory object by calling the <code>"FactoryObject"</code> method.
To call factory methods of objects of an unknown type (such as when you may have a subclass of the class wanted), it is necessary to get a reference to the class's factory object by calling the <code>"FactoryObject"</code> method.
<lang cobol>INVOKE foo-instance "FactoryObject" RETURNING foo-factory
<syntaxhighlight lang="cobolfree">INVOKE some-instance "FactoryObject" RETURNING foo-factory
*> foo-factory can be treated like a normal object reference.
*> foo-factory can be treated like a normal object reference.
INVOKE foo-factory "someMethod"</lang>
INVOKE foo-factory "someMethod"</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
While CoffeeScript does provide a useful class abstraction around its prototype-based inheritance, there aren't any actual classes.
While CoffeeScript does provide a useful class abstraction around its prototype-based inheritance, there aren't any actual classes.
<lang coffeescript>class Foo
<syntaxhighlight lang="coffeescript">class Foo
@staticMethod: -> 'Bar'
@staticMethod: -> 'Bar'


Line 254: Line 267:


foo.instanceMethod() #=> 'Baz'
foo.instanceMethod() #=> 'Baz'
Foo.staticMethod() #=> 'Bar'</lang>
Foo.staticMethod() #=> 'Bar'</syntaxhighlight>



=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
In Common Lisp, classmethods are methods that apply to classes, rather than classes that contain methods.
In Common Lisp, classmethods are methods that apply to classes, rather than classes that contain methods.
<lang lisp>(defclass my-class ()
<syntaxhighlight lang="lisp">(defclass my-class ()
((x
((x
:accessor get-x ;; getter function
:accessor get-x ;; getter function
Line 275: Line 289:


(format t "Value of x^2: ~a~%" (square-x *instance*))
(format t "Value of x^2: ~a~%" (square-x *instance*))
</syntaxhighlight>
</lang>
Output (CLISP v2.49):
Output (CLISP v2.49):
<pre>$ clisp object.cl
<pre>$ clisp object.cl
Line 281: Line 295:
Value of x^2: 100
Value of x^2: 100
</pre>
</pre>



=={{header|D}}==
=={{header|D}}==
<lang d>struct Cat {
<syntaxhighlight lang="d">struct Cat {
static int staticMethod() {
static int staticMethod() {
return 2;
return 2;
Line 319: Line 334:
d = new Dog;
d = new Dog;
assert(d.dynamicMethod() == "Woof!");
assert(d.dynamicMethod() == "Woof!");
}</lang>
}</syntaxhighlight>

=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
This example shows the creation of a simple integer stack object. The object contains "Push" and "Pop" static methods.

<syntaxhighlight lang="Delphi">

{Simple stack interface}

type TSimpleStack = class(TObject)
private
FStack: array of integer;
protected
public
procedure Push(I: integer);
function Pop(var I: integer): boolean;
constructor Create;
end;


{ TSimpleStack implementation }

constructor TSimpleStack.Create;
{Initialize stack by setting size to zero}
begin
SetLength(FStack,0);
end;

function TSimpleStack.Pop(var I: integer): boolean;
{Pop top item off stack into "I" returns False if stack empty}
begin
Result:=Length(FStack)>=1;
if Result then
begin
{Get item from top of stack}
I:=FStack[High(FStack)];
{Delete the top item}
SetLength(FStack,Length(FStack)-1);
end;
end;

procedure TSimpleStack.Push(I: integer);
{Push item on stack by adding to end of array}
begin
{Increase stack size by one}
SetLength(FStack,Length(FStack)+1);
{Insert item}
FStack[High(FStack)]:=I;
end;


procedure ShowStaticMethodCall(Memo: TMemo);
var Stack: TSimpleStack; {Declare stack object}
var I: integer;
begin
{Instanciate stack object}
Stack:=TSimpleStack.Create;
{Push items on stack by calling static method "Push"}
for I:=1 to 10 do Stack.Push(I);
{Call static method "Pop" to retrieve and display stack items}
while Stack.Pop(I) do
begin
Memo.Lines.Add(IntToStr(I));
end;
{release stack memory and delete object}
Stack.Free;
end;



</syntaxhighlight>
{{out}}
<pre>
10
9
8
7
6
5
4
3
2
1
Elapsed Time: 10.571 ms.
</pre>




=={{header|Dragon}}==
=={{header|Dragon}}==
Making an object of class and then calling it.
Making an object of class and then calling it.
<lang Dragon>r = new run()
<syntaxhighlight lang="dragon">r = new run()
r.val()</lang>
r.val()</syntaxhighlight>

=={{header|Dyalect}}==
=={{header|Dyalect}}==


Dyalect supports both instance and static methods. Instance methods have a special <code>this</code> reference that returns an instance. Static method are always invoked through the type name.
Dyalect supports both instance and static methods. Instance methods have a special <code>this</code> reference that returns an instance. Static method are always invoked through the type name.


<lang dyalect>//Static method on a built-in type Integer
<syntaxhighlight lang="dyalect">//Static method on a built-in type Integer
static func Integer.div(x, y) {
static func Integer.Div(x, y) {
x / y
x / y
}
}

//Instance method
//Instance method
func Integer.div(n) {
func Integer.Div(n) {
this / n
this / n
}
}

print(Integer.div(12, 3))
print(Integer.Div(12, 3))
print(12.div(3))</lang>
print(12.Div(3))</syntaxhighlight>


{{out}}
{{out}}
Line 347: Line 449:
<pre>4
<pre>4
4</pre>
4</pre>

=={{header|E}}==
=={{header|E}}==
{{improve|E|Add runnable example.}}
{{improve|E|Add runnable example.}}
A method call in E has the syntax <code><var>recipient</var>.<var>verb</var>(<var>arg1</var>, <var>arg2</var>, <var>...</var>)</code>, where <var>recipient</var> is an expression, <var>verb</var> is an identifier (or a string literal preceded by <code>::</code>), and <var>argN</var> are expressions.
A method call in E has the syntax <code><var>recipient</var>.<var>verb</var>(<var>arg1</var>, <var>arg2</var>, <var>...</var>)</code>, where <var>recipient</var> is an expression, <var>verb</var> is an identifier (or a string literal preceded by <code>::</code>), and <var>argN</var> are expressions.


<lang e>someObject.someMethod(someParameter)</lang>
<syntaxhighlight lang="e">someObject.someMethod(someParameter)</syntaxhighlight>


In E, there are no distinguished "static methods". Instead, it is idiomatic to place methods on the maker of the object. This is very similar to methods on constructors in JavaScript, or class methods in Objective-C.
In E, there are no distinguished "static methods". Instead, it is idiomatic to place methods on the maker of the object. This is very similar to methods on constructors in JavaScript, or class methods in Objective-C.

=={{header|Ecstasy}}==
Calling a method or function in Ecstasy follows roughly the same conventions as in Java and C#, but in order to prevent certain types of bugs, Ecstasy explicitly disallows calling a function <i>as if it were a method</i>.
<syntaxhighlight lang="java">
module CallMethod {
/**
* This is a class with a method and a function.
*/
const Example(String text) {
@Override
String toString() { // <-- this is a method
return $"This is an example with text={text}";
}

static Int oneMoreThan(Int n) { // <-- this is a function
return n+1;
}
}

void run() {
@Inject Console console;

Example example = new Example("hello!");
String methodResult = example.toString(); // <-- call a method
console.print($"Result from calling a method: {methodResult.quoted()}");

// Int funcResult = example.oneMoreThan(12); // <-- compiler error
Int funcResult = Example.oneMoreThan(12); // <-- call a function
console.print($"Results from calling a function: {funcResult}");

// methods and functions are also objects that can be manipulated;
// note that "function String()" === "Function<<>, <String>>"
Method<Example, <>, <String>> method = Example.toString;
function String() func = method.bindTarget(example);
console.print($"Calling a bound method: {func().quoted()}");

// by default, a method with target T converts to a function taking a T;
// Ecstasy refers to this as "Bjarning" (because C++ takes "this" as a param)
val func2 = Example.toString; // <-- type: function String()
console.print($"Calling a Bjarne'd function: {func2(example).quoted()}");

// the function is just an object, and invocation (and in this case, binding,
// as indicated by the '&' operator which requests a reference) is accomplished
// using the "()" operator
val func3 = Example.oneMoreThan; // <-- type: function Int(Int)
val func4 = &func3(13); // <-- type: function Int()
console.print($"Calling a fully bound function: {func4()}");
}
}
</syntaxhighlight>

{{out}}
<pre>
Result from calling a method: "This is an example with text=hello!"
Results from calling a function: 13
Calling a bound method: "This is an example with text=hello!"
Calling a Bjarne'd function: "This is an example with text=hello!"
Calling a fully bound function: 14
</pre>


=={{header|Elena}}==
=={{header|Elena}}==
The message call:
The message call:
<lang elena>
<syntaxhighlight lang="elena">
console.printLine("Hello"," ","World!");
console.printLine("Hello"," ","World!");
</syntaxhighlight>
</lang>

=={{header|Elixir}}==
=={{header|Elixir}}==
Elixir doesn't do objects. Instead of calling methods on object you send messages to processes. Here's an example of a process created with spawn_link which knows how to receive a message "concat" and return a result.
Elixir doesn't do objects. Instead of calling methods on object you send messages to processes. Here's an example of a process created with spawn_link which knows how to receive a message "concat" and return a result.
<lang elixir>
<syntaxhighlight lang="elixir">
defmodule ObjectCall do
defmodule ObjectCall do
def new() do
def new() do
Line 392: Line 551:


IO.puts(obj |> ObjectCall.concat("Hello ", "World!"))
IO.puts(obj |> ObjectCall.concat("Hello ", "World!"))
</syntaxhighlight>
</lang>

=={{header|EMal}}==
{{trans|Wren}}
<syntaxhighlight lang="emal">
type MyClass ^|we are defining a new data type and entering in its static context|^
fun method = void by block do writeLine("static method called") end
model ^|we enter the instance context|^
fun method = void by block do writeLine("instance method called") end
end
type CallAnObjectMethod
var myInstance = MyClass() ^|creating an instance|^
myInstance.method()
MyClass.method()
</syntaxhighlight>
{{out}}
<pre>
instance method called
static method called
</pre>


=={{header|Factor}}==
=={{header|Factor}}==
In Factor, there is no distinction between instance and static methods. Methods are contained in generic words and specialize on a class. Generic words define a <i>method combination</i> so methods know which object(s) to dispatch on. (But most methods dispatch on the object at the top of the data stack.) Under this object model, calling a method is no different than calling any other word.
In Factor, there is no distinction between instance and static methods. Methods are contained in generic words and specialize on a class. Generic words define a <i>method combination</i> so methods know which object(s) to dispatch on. (But most methods dispatch on the object at the top of the data stack.) Under this object model, calling a method is no different than calling any other word.


<lang factor>USING: accessors io kernel literals math sequences ;
<syntaxhighlight lang="factor">USING: accessors io kernel literals math sequences ;
IN: rosetta-code.call-a-method
IN: rosetta-code.call-a-method


Line 416: Line 594:
M: object speak drop "I don't know how to speak!" print ;
M: object speak drop "I don't know how to speak!" print ;


! Place some objects of various classes in a sequence.
! Call speak on various objects.
! Despite being a method, it's called like any other word.
${ dog 0.75 <cat> 0.1 <cat> 10 }
dog speak
! Call speak, a method, just like any other word.
0.75 <cat> speak
[ speak ] each </lang>
0.1 <cat> speak
"bird" speak</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 427: Line 607:
I don't know how to speak!
I don't know how to speak!
</pre>
</pre>

=={{header|Forth}}==
=={{header|Forth}}==
{{works with|4tH|3.62.0}}
{{works with|4tH|3.62.0}}
{{trans|D}}
{{trans|D}}
There are numerous, mutually incompatible object oriented frameworks for Forth. This one works with the FOOS preprocessor extension of [[4tH]].
There are numerous, mutually incompatible object oriented frameworks for Forth. This one works with the FOOS preprocessor extension of [[4tH]].
<lang forth>include lib/compare.4th
<syntaxhighlight lang="forth">include lib/compare.4th
include 4pp/lib/foos.4pp
include 4pp/lib/foos.4pp


Line 471: Line 650:
; \ same for dynamic methods
; \ same for dynamic methods


main</lang>
main</syntaxhighlight>


Works with any ANS Forth
Works with any ANS Forth
Line 477: Line 656:
Needs the FMS-SI (single inheritance) library code located here:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
http://soton.mpeforth.com/flag/fms/index.html
<lang forth>include FMS-SI.f
<syntaxhighlight lang="forth">include FMS-SI.f


:class animal
:class animal
Line 506: Line 685:
Frisky speak \ => meow ok
Frisky speak \ => meow ok
Sparky speak \ => woof ok
Sparky speak \ => woof ok
</syntaxhighlight>
</lang>

=={{header|Fortran}}==
=={{header|Fortran}}==
In modern Fortran a "derived type" concept corresponds to "class" in OOP. Such types have "type bound procedures", i.e. static methods. Procedure pointer components depend on the value of the object (so they are object-bound), can be redefined runtime and correspond approx to instances.
In modern Fortran a "derived type" concept corresponds to "class" in OOP. Such types have "type bound procedures", i.e. static methods. Procedure pointer components depend on the value of the object (so they are object-bound), can be redefined runtime and correspond approx to instances.
<syntaxhighlight lang="fortran">
<lang Fortran>
! type declaration
! type declaration
type my_type
type my_type
Line 526: Line 704:
mytype_object%method2() ! call method2 defined as function
mytype_object%method2() ! call method2 defined as function


</syntaxhighlight>
</lang>

=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>
<syntaxhighlight lang="freebasic">
' FB 1.05.0 Win64
' FB 1.05.0 Win64


Line 554: Line 731:
Print "Press any key to quit the program"
Print "Press any key to quit the program"
Sleep
Sleep
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 560: Line 737:
Hello world!
Hello world!
Hello static world!
Hello static world!
</pre>

=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn FBClassDemo
// Class
ClassRef class = fn MutableStringClass
// Cocoa base class name as human-readable string
print fn StringFromClass( class )
// Instantiate
CFMutableStringRef mutStr = fn MutableStringNew
// Method with single argument
MutableStringSetString( mutStr, @"Hello, World!" )
print mutStr
// Method with multiple arguments
MutableStringReplaceAllOccurrencesOfString( mutStr, @"World", @"Rosetta Code" )
print mutStr
end fn

fn FBClassDemo

HandleEvents
</syntaxhighlight>
{{output}}
<pre>
NSMutableString
Hello, World!
Hello, Rosetta Code!
</pre>
</pre>


=={{header|Go}}==
=={{header|Go}}==
Go distances itself from the word "object" and from many object oriented concepts. It does however have methods. Any user-defined type in Go can have methods and these work very much like "instance methods" of object oriented languages. The examples below illustrate details of Go methods and thus represent the concept of instance methods.
Go distances itself from the word "object" and from many object oriented concepts. It does however have methods. Any user-defined type in Go can have methods and these work very much like "instance methods" of object oriented languages. The examples below illustrate details of Go methods and thus represent the concept of instance methods.
<lang go>type Foo int // some custom type
<syntaxhighlight lang="go">type Foo int // some custom type


// method on the type itself; can be called on that type or its pointer
// method on the type itself; can be called on that type or its pointer
Line 592: Line 800:
Foo.ValueMethod(myValue, someParameter)
Foo.ValueMethod(myValue, someParameter)
(*Foo).PointerMethod(myPointer, someParameter)
(*Foo).PointerMethod(myPointer, someParameter)
(*Foo).ValueMethod(myPointer, someParameter)</lang>
(*Foo).ValueMethod(myPointer, someParameter)</syntaxhighlight>
Go has no direct equivalent to class methods as long as you think of a Go type as a class. A Go ''package'' however can be organized and used much like a class, and in this context, any function exported from the package works much like a class method.
Go has no direct equivalent to class methods as long as you think of a Go type as a class. A Go ''package'' however can be organized and used much like a class, and in this context, any function exported from the package works much like a class method.


An example package:
An example package:
<lang go>package box
<syntaxhighlight lang="go">package box


import "sync/atomic"
import "sync/atomic"
Line 624: Line 832:
func Count() uint32 {
func Count() uint32 {
return atomic.LoadUint32(&sn)
return atomic.LoadUint32(&sn)
}</lang>
}</syntaxhighlight>
Example use:
Example use:
<lang go>package main
<syntaxhighlight lang="go">package main


import "box"
import "box"
Line 641: Line 849:
// Call class method. In Go terms, another exported function.
// Call class method. In Go terms, another exported function.
box.Count()
box.Count()
}</lang>
}</syntaxhighlight>


==Icon and {{header|Unicon}}==
==Icon and {{header|Unicon}}==
Line 647: Line 855:


Unicon has no concept of static methods; all methods are normally invoked using an instance of a class. While it is technically possible to call a method without an instance, it requires knowledge of the underlying implementation, such as the name-mangling conventions, and is non-standard.
Unicon has no concept of static methods; all methods are normally invoked using an instance of a class. While it is technically possible to call a method without an instance, it requires knowledge of the underlying implementation, such as the name-mangling conventions, and is non-standard.
<lang unicon>procedure main()
<syntaxhighlight lang="unicon">procedure main()


bar := foo() # create instance
bar := foo() # create instance
Line 669: Line 877:
initially
initially
L := [cp1]
L := [cp1]
end</lang>
end</syntaxhighlight>
=={{header|Haskell}}==


Haskell doesn't have objects in OOP sence (i.e. first-class sitizens
appearing in runtime with incapsulated state and ability to send messages (methods) to other objects).

Haskell has first-class immutable records with fields of any type, representing abstraction and incapsulation (due to purity).
Polymorphism is implemented via type-classes, which are similar to OOP interfaces.

Dummy example:
<syntaxhighlight lang="haskell">data Obj = Obj { field :: Int, method :: Int -> Int }

-- smart constructor
mkAdder :: Int -> Obj
mkAdder x = Obj x (+x)

-- adding method from a type class
instanse Show Obj where
show o = "Obj " ++ show (field o) </syntaxhighlight>

<pre>*Main> let o1 = Obj 1 (*5)
*Main> field o1
1
*Main> method o1 6
30
*Main> show o1
Obj 1

*Main> let o2 = mkAdder 5
*Main> field o2
5
*Main> method o2 6
11
*Main> show o2
Obj 5</pre>
=={{header|J}}==
=={{header|J}}==


Line 679: Line 920:
Static:
Static:


<lang j>methodName_className_ parameters</lang>
<syntaxhighlight lang="j">methodName_className_ parameters</syntaxhighlight>


and, given an object instance reference:
and, given an object instance reference:


<lang j>objectReference=:'' conew 'className'</lang>
<syntaxhighlight lang="j">objectReference=:'' conew 'className'</syntaxhighlight>


an instance invocation could be:
an instance invocation could be:


<lang j>methodName__objectReference parameters</lang>
<syntaxhighlight lang="j">methodName__objectReference parameters</syntaxhighlight>


Note that J also supports infix notation when using methods. In this case, there will be a second parameter list, on the left of the method reference.
Note that J also supports infix notation when using methods. In this case, there will be a second parameter list, on the left of the method reference.


<lang j>parameters methodName_className_ parameters</lang>
<syntaxhighlight lang="j">parameters methodName_className_ parameters</syntaxhighlight>
or
or
<lang j>parameters methodName__objectReference parameters</lang>
<syntaxhighlight lang="j">parameters methodName__objectReference parameters</syntaxhighlight>


These variations might be useful when building combining words that need to refer to two different kinds of things. But mostly it's to be consistent with the rest of the language.
These variations might be useful when building combining words that need to refer to two different kinds of things. But mostly it's to be consistent with the rest of the language.
Line 699: Line 940:
Finally, note that static methods can be referred to using the same notation as instance methods -- in this case you must have a reference to the class name:
Finally, note that static methods can be referred to using the same notation as instance methods -- in this case you must have a reference to the class name:


<lang j>classReference=: <'className'
<syntaxhighlight lang="j">classReference=: <'className'
methodName__classReference parameters</lang>
methodName__classReference parameters</syntaxhighlight>


This might be useful when you are working with a variety of classes which share a common structure.
This might be useful when you are working with a variety of classes which share a common structure.
Line 706: Line 947:
You can also refer to a dynamic method in the same fashion that you use to refer to a instance method -- in this case you must know the object name (which is a number). For example, to refer to a method on object 123
You can also refer to a dynamic method in the same fashion that you use to refer to a instance method -- in this case you must know the object name (which is a number). For example, to refer to a method on object 123


<lang j>methodName_123_ parameters</lang>
<syntaxhighlight lang="j">methodName_123_ parameters</syntaxhighlight>


This last case can be useful when debugging.
This last case can be useful when debugging.

=={{header|Java}}==
=={{header|Java}}==
Static methods in Java are usually called by using the dot operator on a class name:
Static methods in Java are usually called by using the dot operator on a class name:
<lang java>ClassWithStaticMethod.staticMethodName(argument1, argument2);//for methods with no arguments, use empty parentheses</lang>
<syntaxhighlight lang="java">ClassWithStaticMethod.staticMethodName(argument1, argument2);//for methods with no arguments, use empty parentheses</syntaxhighlight>
Instance methods are called by using the dot operator on an instance:
Instance methods are called by using the dot operator on an instance:
<lang java>ClassWithMethod varName = new ClassWithMethod();
<syntaxhighlight lang="java">ClassWithMethod varName = new ClassWithMethod();
varName.methodName(argument1, argument2);
varName.methodName(argument1, argument2);
//or
//or
new ClassWithMethod().methodName(argument1, argument2);</lang>
new ClassWithMethod().methodName(argument1, argument2);</syntaxhighlight>


Instance methods may not be called on references whose value is <code>null</code> (throws a <code>NullPointerException</code>). <!--Maybe add reflection stuff here too? It might be too complicated or it might not belong here-->
Instance methods may not be called on references whose value is <code>null</code> (throws a <code>NullPointerException</code>). <!--Maybe add reflection stuff here too? It might be too complicated or it might not belong here-->
Line 724: Line 964:


This means that there is no benefit to making a static method call this way, because one can make the call based on the static type that is already known from looking at the code when it is written. Furthermore, such a call may lead to serious pitfalls, leading one to believe that changing the object that it is called on could change the behavior. For example, a common snippet to sleep the thread for 1 second is the following: <code>Thread.currentThread().sleep(1000);</code>. However, since <code>.sleep()</code> is actually a static method, the compiler replaces it with <code>Thread.sleep(1000);</code> (since <code>Thread.currentThread()</code> has a return type of <code>Thread</code>). This makes it clear that the thread that is put to sleep is not under the user's control. However, written as <code>Thread.currentThread().sleep(1000);</code>, it may lead one to falsely believe it to be possible to sleep another thread by doing <code>someOtherThread.sleep(1000);</code> when in fact such a statement would also sleep the current thread.
This means that there is no benefit to making a static method call this way, because one can make the call based on the static type that is already known from looking at the code when it is written. Furthermore, such a call may lead to serious pitfalls, leading one to believe that changing the object that it is called on could change the behavior. For example, a common snippet to sleep the thread for 1 second is the following: <code>Thread.currentThread().sleep(1000);</code>. However, since <code>.sleep()</code> is actually a static method, the compiler replaces it with <code>Thread.sleep(1000);</code> (since <code>Thread.currentThread()</code> has a return type of <code>Thread</code>). This makes it clear that the thread that is put to sleep is not under the user's control. However, written as <code>Thread.currentThread().sleep(1000);</code>, it may lead one to falsely believe it to be possible to sleep another thread by doing <code>someOtherThread.sleep(1000);</code> when in fact such a statement would also sleep the current thread.

=={{header|JavaScript}}==
=={{header|JavaScript}}==
If you have a object called <tt>x</tt> and a method called <tt>y</tt> then you can write:
If you have a object called <tt>x</tt> and a method called <tt>y</tt> then you can write:
<lang javascript>x.y()</lang>
<syntaxhighlight lang="javascript">x.y()</syntaxhighlight>

=={{header|Julia}}==
=={{header|Julia}}==
module Animal
module Animal
Line 759: Line 997:
#
#
masskg(x) = x.weight
masskg(x) = x.weight

=={{header|Kotlin}}==
=={{header|Kotlin}}==
Kotlin does not have static methods as such but they can be easily simulated by 'companion object' methods :
Kotlin does not have static methods, but they can be easily simulated by <code>companion object</code> methods.

<lang scala>class MyClass {
<syntaxhighlight lang="kotlin">class MyClass {
fun instanceMethod(s: String) = println(s)
fun instanceMethod(s: String) = println(s)


Line 770: Line 1,008:
}
}


fun main(args: Array<String>) {
fun main() {
val mc = MyClass()
val mc = MyClass()
mc.instanceMethod("Hello instance world!")
mc.instanceMethod("Hello instance world!")
MyClass.staticMethod("Hello static world!")
MyClass.staticMethod("Hello static world!")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 785: Line 1,023:


In Latitude, everything is an object. Being prototype-oriented, Latitude does not distinguish between classes and instances. Calling a method on either a class or an instance is done by simple juxtaposition.
In Latitude, everything is an object. Being prototype-oriented, Latitude does not distinguish between classes and instances. Calling a method on either a class or an instance is done by simple juxtaposition.
<lang latitude>myObject someMethod (arg1, arg2, arg3).
<syntaxhighlight lang="latitude">myObject someMethod (arg1, arg2, arg3).
MyClass someMethod (arg1, arg2, arg3).</lang>
MyClass someMethod (arg1, arg2, arg3).</syntaxhighlight>
The parentheses on the argument list may be omitted if there is at most one argument and the parse is unambiguous.
The parentheses on the argument list may be omitted if there is at most one argument and the parse is unambiguous.
<lang latitude>myObject someMethod "string constant argument".
<syntaxhighlight lang="latitude">myObject someMethod "string constant argument".
myObject someMethod (argument). ;; Parentheses are necessary here
myObject someMethod (argument). ;; Parentheses are necessary here
myObject someMethod. ;; No arguments</lang>
myObject someMethod. ;; No arguments</syntaxhighlight>
Finally, a colon may be used instead of parentheses, in which case the rest of the line is considered to be the argument list.
Finally, a colon may be used instead of parentheses, in which case the rest of the line is considered to be the argument list.
<lang latitude>myObject someMethod: arg1, arg2, arg3.</lang>
<syntaxhighlight lang="latitude">myObject someMethod: arg1, arg2, arg3.</syntaxhighlight>

=={{header|LFE}}==
=={{header|LFE}}==


Line 804: Line 1,041:


===With Closures===
===With Closures===
<lang lisp>(defmodule aquarium
<syntaxhighlight lang="lisp">(defmodule aquarium
(export all))
(export all))


Line 897: Line 1,134:
(defun get-children-count (object)
(defun get-children-count (object)
(funcall (get-method object 'children-count) object))
(funcall (get-method object 'children-count) object))
</syntaxhighlight>
</lang>


With this done, one can create objects and interact with them. Here is some usage from the LFE REPL:
With this done, one can create objects and interact with them. Here is some usage from the LFE REPL:
<lang lisp>; Load the file and create a fish-class instance:
<syntaxhighlight lang="lisp">; Load the file and create a fish-class instance:


> (slurp '"object.lfe")
> (slurp '"object.lfe")
Line 944: Line 1,181:
children: ["fdcf35983bb496650e558a82e34c9935",
children: ["fdcf35983bb496650e558a82e34c9935",
"3e64e5c20fb742dd88dac1032749c2fd"]
"3e64e5c20fb742dd88dac1032749c2fd"]
ok</lang>
ok</syntaxhighlight>


===With Lightweight Processes===
===With Lightweight Processes===
<lang lisp>(defmodule object
<syntaxhighlight lang="lisp">(defmodule object
(export all))
(export all))


Line 1,047: Line 1,284:


(defun get-children-count (object)
(defun get-children-count (object)
(call-method object 'children-count))</lang>
(call-method object 'children-count))</syntaxhighlight>


Here is some usage from the LFE REPL:
Here is some usage from the LFE REPL:
<lang lisp>; Load the file and create a fish-class instance:
<syntaxhighlight lang="lisp">; Load the file and create a fish-class instance:


> (slurp '"object.lfe")
> (slurp '"object.lfe")
Line 1,094: Line 1,331:
children: ["fdcf35983bb496650e558a82e34c9935",
children: ["fdcf35983bb496650e558a82e34c9935",
"3e64e5c20fb742dd88dac1032749c2fd"]
"3e64e5c20fb742dd88dac1032749c2fd"]
ok</lang>
ok</syntaxhighlight>

=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>-- call static method
<syntaxhighlight lang="lingo">-- call static method
script("MyClass").foo()
script("MyClass").foo()


-- call instance method
-- call instance method
obj = script("MyClass").new()
obj = script("MyClass").new()
obj.foo()</lang>
obj.foo()</syntaxhighlight>

=={{header|Logtalk}}==
=={{header|Logtalk}}==
In Logtalk, class or instance are ''roles'' that an object can play depending on the relations in other objects. Thus, a "class" can be defined by having an object specializing another object and an instance can be defined by having an object instantiating another object. Metaclasses are easily defined and thus a class method is just an instance method defined in the class metaclass.
In Logtalk, class or instance are ''roles'' that an object can play depending on the relations in other objects. Thus, a "class" can be defined by having an object specializing another object and an instance can be defined by having an object instantiating another object. Metaclasses are easily defined and thus a class method is just an instance method defined in the class metaclass.
<lang logtalk>
<syntaxhighlight lang="logtalk">
% avoid infinite metaclass regression by
% avoid infinite metaclass regression by
% making the metaclass an instance of itself
% making the metaclass an instance of itself
Line 1,117: Line 1,352:
:- end_object.
:- end_object.
</syntaxhighlight>
</lang>
<lang logtalk>
<syntaxhighlight lang="logtalk">
:- object(class,
:- object(class,
instantiates(metaclass)).
instantiates(metaclass)).
Line 1,128: Line 1,363:
:- end_object.
:- end_object.
</syntaxhighlight>
</lang>
<lang logtalk>
<syntaxhighlight lang="logtalk">
:- object(instance,
:- object(instance,
instantiates(class)).
instantiates(class)).


:- end_object.
:- end_object.
</syntaxhighlight>
</lang>
Testing:
Testing:
<lang logtalk>
<syntaxhighlight lang="logtalk">
| ?- class::me(Me).
| ?- class::me(Me).
Me = class
Me = class
Line 1,144: Line 1,379:
Class = class
Class = class
yes
yes
</syntaxhighlight>
</lang>

=={{header|Lua}}==
=={{header|Lua}}==
Lua does not provide a specific OO implementation, but its metatable mechanism and sugar for method-like calls does make it easy to implement and use such as system, as evidenced by its multitude of class libraries in particular.
Lua does not provide a specific OO implementation, but its metatable mechanism and sugar for method-like calls does make it easy to implement and use such as system, as evidenced by its multitude of class libraries in particular.


Instance methods, in their most basic form, are simply function calls where the calling object reference is duplicated and passed as the first argument. Lua offers some syntactical sugar to facilitate this, via the colon operator:
Instance methods, in their most basic form, are simply function calls where the calling object reference is duplicated and passed as the first argument. Lua offers some syntactical sugar to facilitate this, via the colon operator:
<lang lua>local object = { name = "foo", func = function (self) print(self.name) end }
<syntaxhighlight lang="lua">local object = { name = "foo", func = function (self) print(self.name) end }


object:func() -- with : sugar
object:func() -- with : sugar
object.func(object) -- without : sugar</lang>
object.func(object) -- without : sugar</syntaxhighlight>


Using metatables, and specifically the __index metamethod, it is possible to call a method stored in an entirely different table, while still passing the object used for the actual call:
Using metatables, and specifically the __index metamethod, it is possible to call a method stored in an entirely different table, while still passing the object used for the actual call:
<lang lua>local methods = { }
<syntaxhighlight lang="lua">local methods = { }
function methods:func () -- if a function is declared using :, it is given an implicit 'self' parameter
function methods:func () -- if a function is declared using :, it is given an implicit 'self' parameter
print(self.name)
print(self.name)
Line 1,164: Line 1,398:


object:func() -- with : sugar
object:func() -- with : sugar
methods.func(object) -- without : sugar</lang>
methods.func(object) -- without : sugar</syntaxhighlight>


Lua does not have a specific way of handling static methods, but similarly to Go, they could simply be implemented as regular functions inside of a module.
Lua does not have a specific way of handling static methods, but similarly to Go, they could simply be implemented as regular functions inside of a module.


Example module, named <code>box.lua</code>:
Example module, named <code>box.lua</code>:
<lang lua>local count = 0
<syntaxhighlight lang="lua">local count = 0
local box = { }
local box = { }
local boxmt = { __index = box }
local boxmt = { __index = box }
Line 1,184: Line 1,418:
return count
return count
end
end
return M</lang>
return M</syntaxhighlight>


Example use:
Example use:
<lang lua>local box = require 'box'
<syntaxhighlight lang="lua">local box = require 'box'


local b = box.new()
local b = box.new()


print(b:tellSecret())
print(b:tellSecret())
print(box.count())</lang>
print(box.count())</syntaxhighlight>

=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
In M2000 there are some kinds of objects. Group is the one type object. We can compose members to groups, with functions, operators, modules, events, and inner groups, among other members of type pointer to object. Another type is the COM type. Here we see the Group object
In M2000 there are some kinds of objects. Group is an object. We can compose members to groups, with functions, operators, modules, events, and inner groups, among other members of type pointer to object. Another type is the COM type. Here we see the Group object
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Module CheckIt {
\\ A class definition is a function which return a Group
\\ A class definition is a function which return a Group
Line 1,245: Line 1,478:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>




=={{header|Maple}}==
=={{header|Maple}}==
There is no real difference in how you call a static or instance method.
There is no real difference in how you call a static or instance method.
<lang Maple># Static
<syntaxhighlight lang="maple"># Static
Method( obj, other, arg );</lang>
Method( obj, other, arg );</syntaxhighlight>
<lang Maple># Instance
<syntaxhighlight lang="maple"># Instance
Method( obj, other, arg );</lang>
Method( obj, other, arg );</syntaxhighlight>

=={{header|MiniScript}}==
=={{header|MiniScript}}==
MiniScript uses prototype-based inheritance, so the only difference between a static method and an instance method is in whether it uses the <code>self</code> pseudo-keyword.
MiniScript uses prototype-based inheritance, so the only difference between a static method and an instance method is in whether it uses the <code>self</code> pseudo-keyword.
<lang MiniScript>Dog = {}
<syntaxhighlight lang="miniscript">Dog = {}
Dog.name = ""
Dog.name = ""
Dog.help = function()
Dog.help = function()
Line 1,271: Line 1,501:


Dog.help // calling a "class method"
Dog.help // calling a "class method"
fido.speak // calling an "instance method"</lang>
fido.speak // calling an "instance method"</syntaxhighlight>


{{out}}
{{out}}
<pre>This class represents dogs.
<pre>This class represents dogs.
Fido says Woof!</pre>
Fido says Woof!</pre>

=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>class MyClass
<syntaxhighlight lang="nanoquery">class MyClass
declare static id = 5
declare static id = 5
declare MyName
declare MyName
Line 1,304: Line 1,533:
// and call the class method
// and call the class method
myclass = new(MyClass, "test")
myclass = new(MyClass, "test")
println myclass.getName()</lang>
println myclass.getName()</syntaxhighlight>
{{out}}
{{out}}
<pre>5
<pre>5
test</pre>
test</pre>

=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>// Static
<syntaxhighlight lang="nemerle">// Static
MyClass.Method(someParameter);
MyClass.Method(someParameter);
// Instance
// Instance
myInstance.Method(someParameter);</lang>
myInstance.Method(someParameter);</syntaxhighlight>

=={{header|NetRexx}}==
=={{header|NetRexx}}==
Like [[#Java|Java]], static methods in NetRexx are called by using the dot operator on a class name:
Like [[#Java|Java]], static methods in NetRexx are called by using the dot operator on a class name:
<lang NetRexx>SomeClass.staticMethod()</lang>
<syntaxhighlight lang="netrexx">SomeClass.staticMethod()</syntaxhighlight>
Instance methods are called by using the dot operator on an instance:
Instance methods are called by using the dot operator on an instance:
<lang NetRexx>objectInstance = SomeClass() -- create a new instance of the class
<syntaxhighlight lang="netrexx">objectInstance = SomeClass() -- create a new instance of the class
objectInstance.instanceMethod() -- call the instance method
objectInstance.instanceMethod() -- call the instance method


SomeClass().instanceMethod() -- same as above; create a new instance of the class and call the instance method immediately</lang>
SomeClass().instanceMethod() -- same as above; create a new instance of the class and call the instance method immediately</syntaxhighlight>

=={{header|Nim}}==
=={{header|Nim}}==
In Nim there are no object methods, but regular procedures can be called with method call syntax:
In Nim there are no object methods, but regular procedures can be called with method call syntax:
<lang nim>var x = @[1, 2, 3]
<syntaxhighlight lang="nim">var x = @[1, 2, 3]
add(x, 4)
add(x, 4)
x.add(5)</lang>
x.add(5)</syntaxhighlight>

=={{header|OASYS Assembler}}==
=={{header|OASYS Assembler}}==
The OASYS runtime is strange; all classes share the same methods and properties, there are no static methods and properties, and there are no procedures/functions other than methods on objects. However, the initialization method can be called on a null object (no other method has this possibility).
The OASYS runtime is strange; all classes share the same methods and properties, there are no static methods and properties, and there are no procedures/functions other than methods on objects. However, the initialization method can be called on a null object (no other method has this possibility).


The following code calls a method called <tt>&amp;GO</tt> on the current object:
The following code calls a method called <tt>&amp;GO</tt> on the current object:
<lang oasys_oaa>+&GO</lang>
<syntaxhighlight lang="oasys_oaa">+&GO</syntaxhighlight>

=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
ClassName->some_function(); # call class function
ClassName->some_function(); # call class function
instance->some_method(); # call instance method</lang>
instance->some_method(); # call instance method</syntaxhighlight>
Objeck uses the same syntax for instance and class method calls. In Objeck, functions are the equivalent of public static methods.
Objeck uses the same syntax for instance and class method calls. In Objeck, functions are the equivalent of public static methods.

=={{header|Object Pascal}}==
=={{header|Object Pascal}}==


Object Pascal as implemented in Delphi and Free Pascal supports both static (known in Pascal as class method) and instance methods. Free Pascal has two levels of static methods, one using the class keyword and one using both the class and the static keywords. A class method can be called in Pascal, while a static class method could be called even from C, that's the main difference.
Object Pascal as implemented in Delphi and Free Pascal supports both static (known in Pascal as class method) and instance methods. Free Pascal has two levels of static methods, one using the class keyword and one using both the class and the static keywords. A class method can be called in Pascal, while a static class method could be called even from C, that's the main difference.


<lang pascal>// Static (known in Pascal as class method)
<syntaxhighlight lang="pascal">// Static (known in Pascal as class method)
MyClass.method(someParameter);
MyClass.method(someParameter);


// Instance
// Instance
myInstance.method(someParameter);
myInstance.method(someParameter);
</syntaxhighlight>
</lang>

=={{header|Objective-C}}==
=={{header|Objective-C}}==
In Objective-C, calling an instance method is sending a message to an instance, and calling a class method is sending a message to a class object. Class methods are inherited through inheritance of classes. All messages (whether sent to a normal object or class object) are resolved dynamically at runtime, hence there are no "static" methods (see also: Smalltalk).
In Objective-C, calling an instance method is sending a message to an instance, and calling a class method is sending a message to a class object. Class methods are inherited through inheritance of classes. All messages (whether sent to a normal object or class object) are resolved dynamically at runtime, hence there are no "static" methods (see also: Smalltalk).
<lang objc>// Class
<syntaxhighlight lang="objc">// Class
[MyClass method:someParameter];
[MyClass method:someParameter];
// or equivalently:
// or equivalently:
Line 1,369: Line 1,591:


// Method with no arguments
// Method with no arguments
[myInstance method];</lang>
[myInstance method];</syntaxhighlight>

=={{header|OCaml}}==
=={{header|OCaml}}==


We can only call the method of an instantiated object:
We can only call the method of an instantiated object:


<lang ocaml>my_obj#my_meth params</lang>
<syntaxhighlight lang="ocaml">my_obj#my_meth params</syntaxhighlight>

=={{header|Oforth}}==
=={{header|Oforth}}==
When a method is called, the top of the stack is used as the object on which the method will be applyed :
When a method is called, the top of the stack is used as the object on which the method will be applyed :
<lang Oforth>1.2 sqrt</lang>
<syntaxhighlight lang="oforth">1.2 sqrt</syntaxhighlight>


For class methods, the top of the stack must be a class (which is also an object of Class class) :
For class methods, the top of the stack must be a class (which is also an object of Class class) :
<lang Oforth>Date now</lang>
<syntaxhighlight lang="oforth">Date now</syntaxhighlight>

=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang ooRexx>say "pi:" .circle~pi
<syntaxhighlight lang="oorexx">say "pi:" .circle~pi
c=.circle~new(1)
c=.circle~new(1)
say "c~area:" c~area
say "c~area:" c~area
Line 1,414: Line 1,633:
Say self~class
Say self~class
Say self
Say self
return self~class~pi * radius * radius </lang>
return self~class~pi * radius * radius </syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>pi: 3.14159265358979323
<pre>pi: 3.14159265358979323
Line 1,421: Line 1,640:
c~area: 3.14159265
c~area: 3.14159265
10 circles were created</pre>
10 circles were created</pre>

=={{header|Perl}}==
=={{header|Perl}}==
<lang perl># Class method
<syntaxhighlight lang="perl"># Class method
MyClass->classMethod($someParameter);
MyClass->classMethod($someParameter);
# Equivalently using a class name
# Equivalently using a class name
Line 1,439: Line 1,657:
# the package and calling it on the class name or object reference explicitly
# the package and calling it on the class name or object reference explicitly
MyClass::classMethod('MyClass', $someParameter);
MyClass::classMethod('MyClass', $someParameter);
MyClass::method($myInstance, $someParameter);</lang>
MyClass::method($myInstance, $someParameter);</syntaxhighlight>

=={{header|Perl 6}}==
{{works with|Rakudo|2015.12}}
=== Basic method calls ===
<lang perl6>class Thing {
method regular-example() { say 'I haz a method' }

multi method multi-example() { say 'No arguments given' }
multi method multi-example(Str $foo) { say 'String given' }
multi method multi-example(Int $foo) { say 'Integer given' }
};

# 'new' is actually a method, not a special keyword:
my $thing = Thing.new;

# No arguments: parentheses are optional
$thing.regular-example;
$thing.regular-example();
$thing.multi-example;
$thing.multi-example();

# Arguments: parentheses or colon required
$thing.multi-example("This is a string");
$thing.multi-example: "This is a string";
$thing.multi-example(42);
$thing.multi-example: 42;

# Indirect (reverse order) method call syntax: colon required
my $foo = new Thing: ;
multi-example $thing: 42;
</lang>

=== Meta-operators ===

The <code>.</code> operator can be decorated with meta-operators.

<lang perl6>
my @array = <a z c d y>;
@array .= sort; # short for @array = @array.sort;

say @array».uc; # uppercase all the strings: A C D Y Z
</lang>

=== Classless methods ===

A method that is not in a class can be called by using the <code>&</code> sigil explicitly.

<lang perl6>
my $object = "a string"; # Everything is an object.
my method example-method {
return "This is { self }.";
}

say $object.&example-method; # Outputs "This is a string."
</lang>

=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/Class}}
Class methods are only "static" (not really a Phix term) if you don't override them.<br>
Class methods are only "static" (not really a Phix term) if you don't override them.<br>
Phix does not demand that all routines be inside classes; traditional standalone routines are "static" in every sense.<br>
Phix does not demand that all routines be inside classes; traditional standalone routines are "static" in every sense.<br>
There is no way to call a class method without an instance, since "this" will typecheck even if not otherwise used.
There is no way to call a class method without an instance, since "this" will typecheck even if not otherwise used.
<!--<syntaxhighlight lang="phix">(notonline)-->
Needs 0.8.1+
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no class in p2js)</span>
<lang Phix>class test
<span style="color: #008080;">class</span> <span style="color: #000000;">test</span>
string msg = "this is a test"
<span style="color: #004080;">string</span> <span style="color: #000000;">msg</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"this is a test"</span>
procedure show() ?this.msg end procedure
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show</span><span style="color: #0000FF;">()</span> <span style="color: #0000FF;">?</span><span style="color: #7060A8;">this</span><span style="color: #0000FF;">.</span><span style="color: #000000;">msg</span> <span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
procedure inst() ?"this is dynamic" end procedure
<span style="color: #008080;">procedure</span> <span style="color: #000000;">inst</span><span style="color: #0000FF;">()</span> <span style="color: #0000FF;">?</span><span style="color: #008000;">"this is dynamic"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
end class
<span style="color: #008080;">end</span> <span style="color: #008080;">class</span>
test t = new()
<span style="color: #000000;">test</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new</span><span style="color: #0000FF;">()</span>
t.show() -- prints "this is a test"
<span style="color: #000000;">t</span><span style="color: #0000FF;">.</span><span style="color: #000000;">show</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- prints "this is a test"</span>
t.inst() -- prints "this is dynamic"
<span style="color: #000000;">t</span><span style="color: #0000FF;">.</span><span style="color: #000000;">inst</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- prints "this is dynamic"</span>
t.inst = t.show
<span style="color: #000000;">t</span><span style="color: #0000FF;">.</span><span style="color: #000000;">inst</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">.</span><span style="color: #000000;">show</span>
t.inst() -- prints "this is a test"</lang>
<span style="color: #000000;">t</span><span style="color: #0000FF;">.</span><span style="color: #000000;">inst</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- prints "this is a test"</span>

<!--</syntaxhighlight>-->
=={{header|PHP}}==
=={{header|PHP}}==
<lang php>// Static method
<syntaxhighlight lang="php">// Static method
MyClass::method($someParameter);
MyClass::method($someParameter);
// In PHP 5.3+, static method can be called on a string of the class name
// In PHP 5.3+, static method can be called on a string of the class name
Line 1,521: Line 1,685:


// Instance method
// Instance method
$myInstance->method($someParameter);</lang>
$myInstance->method($someParameter);</syntaxhighlight>

=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Method invocation is syntactically equivalent to normal function calls. Method names have a trailing '>' by convention.
Method invocation is syntactically equivalent to normal function calls. Method names have a trailing '>' by convention.
<lang PicoLisp>(foo> MyClass)
<syntaxhighlight lang="picolisp">(foo> MyClass)
(foo> MyObject)</lang>
(foo> MyObject)</syntaxhighlight>
=={{header|Pike}}==
=={{header|Pike}}==
Pike does not have static methods. (the <code>static</code> modifier in Pike is similar to <code>protected</code> in C++).
Pike does not have static methods. (the <code>static</code> modifier in Pike is similar to <code>protected</code> in C++).


regular methods can be called in these ways:
regular methods can be called in these ways:
<lang Pike>obj->method();
<syntaxhighlight lang="pike">obj->method();
obj["method"]();
obj["method"]();
call_function(obj->method);
call_function(obj->method);
call_function(obj["method"]);</lang>
call_function(obj["method"]);</syntaxhighlight>
<code>call_function()</code> is rarely used anymore.
<code>call_function()</code> is rarely used anymore.


because <code>()</code> is actually an operator that is applied to a function reference, the following is also possible:
because <code>()</code> is actually an operator that is applied to a function reference, the following is also possible:
<lang Pike>function func = obj->method;
<syntaxhighlight lang="pike">function func = obj->method;
func();</lang>
func();</syntaxhighlight>
as alternative to static function, modules are used. a module is essentially a static class. a function in a module can be called like this:
as alternative to static function, modules are used. a module is essentially a static class. a function in a module can be called like this:
<lang Pike>module.func();
<syntaxhighlight lang="pike">module.func();
module["func"]();</lang>
module["func"]();</syntaxhighlight>
it should be noted that <code>module.func</code> is resolved at compile time while <code>module["func"]</code> is resolved at runtime.
it should be noted that <code>module.func</code> is resolved at compile time while <code>module["func"]</code> is resolved at runtime.

=={{header|PL/SQL}}==
=={{header|PL/SQL}}==
<lang PLSQL>create or replace TYPE myClass AS OBJECT (
<syntaxhighlight lang="plsql">create or replace TYPE myClass AS OBJECT (
-- A class needs at least one member even though we don't use it
-- A class needs at least one member even though we don't use it
dummy NUMBER,
dummy NUMBER,
Line 1,572: Line 1,734:
DBMS_OUTPUT.put_line( myClass.static_method() );
DBMS_OUTPUT.put_line( myClass.static_method() );
DBMS_OUTPUT.put_line( myInstance.instance_method() );
DBMS_OUTPUT.put_line( myInstance.instance_method() );
END;/</lang>
END;/</syntaxhighlight>

=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang PowerShell>$Date = Get-Date
<syntaxhighlight lang="powershell">$Date = Get-Date
$Date.AddDays( 1 )
$Date.AddDays( 1 )
[System.Math]::Sqrt( 2 )</lang>
[System.Math]::Sqrt( 2 )</syntaxhighlight>

=={{header|Processing}}==
=={{header|Processing}}==
<lang processing>// define a rudimentary class
<syntaxhighlight lang="processing">// define a rudimentary class
class HelloWorld
class HelloWorld
{
{
Line 1,600: Line 1,760:


// and call the instance method
// and call the instance method
hello.sayGoodbye();</lang>
hello.sayGoodbye();</syntaxhighlight>

=={{header|Python}}==
=={{header|Python}}==
<lang python>class MyClass(object):
<syntaxhighlight lang="python">class MyClass(object):
@classmethod
@classmethod
def myClassMethod(self, x):
def myClassMethod(self, x):
Line 1,626: Line 1,785:
# You can also call class or static methods on an instance, which will simply call it on the instance's class
# You can also call class or static methods on an instance, which will simply call it on the instance's class
myInstance.myClassMethod(someParameter)
myInstance.myClassMethod(someParameter)
myInstance.myStaticMethod(someParameter)</lang>
myInstance.myStaticMethod(someParameter)</syntaxhighlight>
=={{header|Quackery}}==


Quackery is not an Object Oriented language. However it is possible to create a zen-like "distilled essence of object-orientation" in just a few lines of code.

Note that Quackery also does not have operator overloading (but see
[https://rosettacode.org/wiki/Modular_arithmetic3Quackery Modular arithmetic#Quackery] for an illustration of how this can be achieved) so there is limited inheritance of methods possible - here only the methods <code>localise</code> and <code>delocalise</code> are common to all object types.

(It would be possible to extend this technique to a more fully-fledged object oriented system. See Dick Pountain's slim volume "Object Oriented FORTH: Implementation of Data Structures" (pub. 1987) for an example of doing so in Forth; a language to which Quackery is related, but slightly less amenable to such shenanigans.)

<syntaxhighlight lang="quackery">( ---------------- zen object orientation -------------- )
[ immovable
]this[ swap do ]done[ ] is object ( --> )
[ ]'[ ] is method ( --> [ )
[ method
[ dup share
swap put ] ] is localise ( --> [ )
[ method [ release ] ] is delocalise ( --> [ )
( -------------- example: counter methods -------------- )

( to create a counter object, use:
"[ object 0 ] is 'name' ( [ --> )" )
[ method
[ 0 swap replace ] ] is reset-counter ( --> [ )
[ method
[ 1 swap tally ] ] is increment-counter ( --> [ )
[ method [ share ] ] is report-counter ( --> [ )
( -------------------- demonstration ------------------- )
say 'Creating counter object: "mycounter".' cr cr
[ object 0 ] is mycounter ( [ --> )
say "Initial value of mycounter: "
report-counter mycounter echo cr cr
say "Incrementing mycounter three times." cr
3 times [ increment-counter mycounter ]
say "Current value of mycounter: "
report-counter mycounter echo cr cr
say "Localising mycounter." cr cr
localise mycounter
say " Current value of mycounter: "
report-counter mycounter echo cr cr
say " Resetting mycounter." cr
reset-counter mycounter
say " Current value of mycounter: "
report-counter mycounter echo cr cr
say " Incrementing mycounter six times." cr
6 times [ increment-counter mycounter ]
say " Current value of mycounter: "
report-counter mycounter echo cr cr
say "Delocalising mycounter." cr cr
delocalise mycounter
say "Current value of mycounter: "
report-counter mycounter echo cr cr
say "Resetting mycounter." cr
reset-counter mycounter
say "Current value of mycounter: "
report-counter mycounter echo cr cr</syntaxhighlight>

{{out}}

<pre>Creating counter object: "mycounter".

Initial value of mycounter: 0

Incrementing mycounter three times.
Current value of mycounter: 3

Localising mycounter.

Current value of mycounter: 3

Resetting mycounter.
Current value of mycounter: 0

Incrementing mycounter six times.
Current value of mycounter: 6

Delocalising mycounter.

Current value of mycounter: 3

Resetting mycounter.
Current value of mycounter: 0</pre>
=={{header|Racket}}==
=={{header|Racket}}==


The following snippet shows a call to the <tt>start</tt> method of the <tt>timer%</tt> class.
The following snippet shows a call to the <tt>start</tt> method of the <tt>timer%</tt> class.


<lang racket>#lang racket/gui
<syntaxhighlight lang="racket">#lang racket/gui


(define timer (new timer%))
(define timer (new timer%))
(send timer start 100)</lang>
(send timer start 100)</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
=== Basic method calls ===
<syntaxhighlight lang="raku" line>class Thing {
method regular-example() { say 'I haz a method' }


multi method multi-example() { say 'No arguments given' }
multi method multi-example(Str $foo) { say 'String given' }
multi method multi-example(Int $foo) { say 'Integer given' }
};

# 'new' is actually a method, not a special keyword:
my $thing = Thing.new;

# No arguments: parentheses are optional
$thing.regular-example;
$thing.regular-example();
$thing.multi-example;
$thing.multi-example();

# Arguments: parentheses or colon required
$thing.multi-example("This is a string");
$thing.multi-example: "This is a string";
$thing.multi-example(42);
$thing.multi-example: 42;

# Indirect (reverse order) method call syntax: colon required
my $foo = new Thing: ;
multi-example $thing: 42;
</syntaxhighlight>

=== Meta-operators ===

The <code>.</code> operator can be decorated with meta-operators.

<syntaxhighlight lang="raku" line>
my @array = <a z c d y>;
@array .= sort; # short for @array = @array.sort;

say @array».uc; # uppercase all the strings: A C D Y Z
</syntaxhighlight>

=== Classless methods ===

A method that is not in a class can be called by using the <code>&</code> sigil explicitly.

<syntaxhighlight lang="raku" line>
my $object = "a string"; # Everything is an object.
my method example-method {
return "This is { self }.";
}

say $object.&example-method; # Outputs "This is a string."
</syntaxhighlight>
=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
new point { print() }
new point { print() }
Class Point
Class Point
x = 10 y = 20 z = 30
x = 10 y = 20 z = 30
func print see x + nl + y + nl + z + nl
func print see x + nl + y + nl + z + nl
</syntaxhighlight>
</lang>
<lang ring>
<syntaxhighlight lang="ring">
o1 = new System.output.console
o1 = new System.output.console
o1.print("Hello World")
o1.print("Hello World")
Line 1,652: Line 1,970:
Func Print cText
Func Print cText
see cText + nl
see cText + nl
</syntaxhighlight>
</lang>

=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby># Class method
<syntaxhighlight lang="ruby"># Class method
MyClass.some_method(some_parameter)
MyClass.some_method(some_parameter)


Line 1,664: Line 1,981:


# Instance method
# Instance method
my_instance.method(some_parameter)
my_instance.a_method(some_parameter)


# The parentheses are optional
# The parentheses are optional
my_instance.method some_parameter
my_instance.a_method some_parameter


# Calling a method with no parameters
# Calling a method with no parameters
my_instance.another_method</lang>
my_instance.another_method</syntaxhighlight>

=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>struct Foo;
<syntaxhighlight lang="rust">struct Foo;


impl Foo {
impl Foo {
Line 1,703: Line 2,019:
let lots_of_references = &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&foo;
let lots_of_references = &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&foo;
println!("The answer to life is still {}." lots_of_references.get_the_answer_to_life());
println!("The answer to life is still {}." lots_of_references.get_the_answer_to_life());
}</lang>
}</syntaxhighlight>

=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>/* This class implicitly includes a constructor which accepts an Int and
<syntaxhighlight lang="scala">/* This class implicitly includes a constructor which accepts an Int and
* creates "val variable1: Int" with that value.
* creates "val variable1: Int" with that value.
*/
*/
Line 1,729: Line 2,044:
assert(n.memberVal == 3)
assert(n.memberVal == 3)
println("Successfully completed without error.")
println("Successfully completed without error.")
}</lang>
}</syntaxhighlight>

=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>class MyClass {
<syntaxhighlight lang="ruby">class MyClass {
method foo(arg) { say arg }
method foo(arg) { say arg }
}
}
Line 1,754: Line 2,068:


# Alternatively, by asking for a method
# Alternatively, by asking for a method
instance.method(:foo)(arg);</lang>
instance.method(:foo)(arg);</syntaxhighlight>

=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
In Smalltalk, calling an instance method is sending a message to an instance, and calling a class method is sending a message to a class object. Class methods are inherited through inheritance of classes. All messages (whether sent to a normal object or class object) are resolved dynamically at runtime, hence strictly speaking, there are no "static" methods. Often in literature, Smalltalk's class messages are described as synonymous to static function calls. This is wrong, because class methods can be overwritten in subclasses just as any other message.
In Smalltalk, calling an instance method is sending a message to an instance, and calling a class method is sending a message to a class object. Class methods are inherited through inheritance of classes. All messages (whether sent to a normal object or class object) are resolved dynamically at runtime, hence strictly speaking, there are no "static" methods. Often in literature, Smalltalk's class messages are described as synonymous to static function calls. This is wrong, because class methods can be overwritten in subclasses just as any other message.
Classes are first class objects, meaning that references to them can be passed as argument, stored in other objects or returned as the result of a message send. This makes some of the common design patterns which deal with creation of objects trivial or even superfluous. (see also: ObjectiveC)
Classes are first class objects, meaning that references to them can be passed as argument, stored in other objects or returned as the result of a message send. This makes some of the common design patterns which deal with creation of objects trivial or even superfluous. (see also: ObjectiveC)


<lang smalltalk>" Class "
<syntaxhighlight lang="smalltalk">" Class "
MyClass selector: someArgument .
MyClass selector: someArgument .
" or equivalently "
" or equivalently "
Line 1,776: Line 2,089:


" Binary (operator) message"
" Binary (operator) message"
myInstance + argument .</lang>
myInstance + argument .</syntaxhighlight>




Example for dynamic class determination:
Example for dynamic class determination:
<lang smalltalk>theCar := (someCondition ifTrue:[ Ford ] ifFalse: [ Jaguar ]) new.</lang>
<syntaxhighlight lang="smalltalk">theCar := (someCondition ifTrue:[ Ford ] ifFalse: [ Jaguar ]) new.</syntaxhighlight>


Message names (selectors) can be chosen or constructed dynamically at runtime. For example:
Message names (selectors) can be chosen or constructed dynamically at runtime. For example:
<lang smalltalk>whichMessage := #( #'red' #'green' #'blue') at: computedIndex.
<syntaxhighlight lang="smalltalk">whichMessage := #( #'red' #'green' #'blue') at: computedIndex.
foo perform: whichMessage</lang>
foo perform: whichMessage</syntaxhighlight>


or:
or:


<lang smalltalk>theMessage := ('handleFileType' , suffix) asSymbol.
<syntaxhighlight lang="smalltalk">theMessage := ('handleFileType' , suffix) asSymbol.
foo perform: theMessage.</lang>
foo perform: theMessage.</syntaxhighlight>
This is often sometimes used as a dispatch mechanism (also, to implement state machines, for example).
This is often sometimes used as a dispatch mechanism (also, to implement state machines, for example).


Of course, especially with all that dynamics, a selector for an unimplemented message might be encountered. This raises a MessageNotUnderstood exception (runtime exception).
Of course, especially with all that dynamics, a selector for an unimplemented message might be encountered. This raises a MessageNotUnderstood exception (runtime exception).
<lang smalltalk>[
<syntaxhighlight lang="smalltalk">[
foo perform: theMessage
foo perform: theMessage
] on: MessageNotUnderstood do:[
] on: MessageNotUnderstood do:[
Dialog information: 'sorry'
Dialog information: 'sorry'
]</lang>
]</syntaxhighlight>

=={{header|SuperCollider}}==
=={{header|SuperCollider}}==
In SuperCollider, classes are objects. To call a class or object method, a message is passed to the class or the object instance. In the implementation, class method names are prefixed with an asterix, all other methods are instance methods.
In SuperCollider, classes are objects. To call a class or object method, a message is passed to the class or the object instance. In the implementation, class method names are prefixed with an asterix, all other methods are instance methods.
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
SomeClass {
SomeClass {
Line 1,818: Line 2,130:
a = SomeClass.new;
a = SomeClass.new;
a.someInstanceMethod;
a.someInstanceMethod;
</syntaxhighlight>
</lang>

=={{header|Swift}}==
=={{header|Swift}}==
In Swift, instance methods can be declared on structs, enums, and classes. "Type methods", which include static methods for structs and enums, and class methods for classes, can be called on the type. Class methods are inherited through inheritance of classes, and are resolved dynamically at runtime like instance methods. (see also: Smalltalk).
In Swift, instance methods can be declared on structs, enums, and classes. "Type methods", which include static methods for structs and enums, and class methods for classes, can be called on the type. Class methods are inherited through inheritance of classes, and are resolved dynamically at runtime like instance methods. (see also: Smalltalk).
<lang swift>// Class
<syntaxhighlight lang="swift">// Class
MyClass.method(someParameter)
MyClass.method(someParameter)
// or equivalently:
// or equivalently:
Line 1,832: Line 2,143:


// Method with multiple arguments
// Method with multiple arguments
myInstance.method(red:arg1, green:arg2, blue:arg3)</lang>
myInstance.method(red:arg1, green:arg2, blue:arg3)</syntaxhighlight>

=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>package require Tcl 8.6
<syntaxhighlight lang="tcl">package require Tcl 8.6
# "Static" (on class object)
# "Static" (on class object)
MyClass mthd someParameter
MyClass mthd someParameter


# Instance
# Instance
$myInstance mthd someParameter</lang>
$myInstance mthd someParameter</syntaxhighlight>
=={{header|TXR}}==

TXR Lisp method invocation syntax is <code>obj.(method args...)</code>.

Static methods are just functions that don't take an object as an argument. The above notation, therefore, normally isn't used, rather the functional square brackets: <code>[obj.function args...]</code>.

The <code>defstruct</code> clause <code>:method</code> is equivalent to <code>:function</code> except that it requires at least one argument, the leftmost one denoting the object.

The <code>obj.(method args...)</code> could be used to call a static function; it would pass <code>obj</code> as the leftmost argument. Vice versa, the square bracket call notation can be used to invoke a method; the object has to be manually inserted: <code>[obj.function obj args...]</code>.

<syntaxhighlight lang="txrlisp">(defvarl thing-count 0)

(defstruct thing ()
(call-count 0)

(:init (me)
(inc thing-count))
(:function get-thing-count () thing-count)
(:method get-call-count (me) (inc me.call-count)))

(let ((t1 (new thing))
(t2 (new thing)))
(prinl t1.(get-call-count)) ;; prints 1
(prinl t1.(get-call-count)) ;; prints 2
(prinl t1.(get-call-count)) ;; prints 3
(prinl t2.(get-call-count)) ;; prints 1
(prinl t2.(get-call-count)) ;; prints 2
(prinl t2.(get-call-count)) ;; prints 3
(prinl [t1.get-thing-count]) ;; prints 2
(prinl [t2.get-thing-count])) ;; prints 2</syntaxhighlight>

{{out}}
<pre>1
2
3
1
2
3
2
2</pre>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa># create an instance of the built-in file class
<syntaxhighlight lang="ursa"># create an instance of the built-in file class
decl file f
decl file f


# call the file.open method
# call the file.open method
f.open "filename.txt"</lang>
f.open "filename.txt"</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
First we have to create a class module named "myObject" :
First we have to create a class module named "myObject" :
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
Option Explicit


Line 1,864: Line 2,215:
If myStr <> "" Then strTemp = myStr
If myStr <> "" Then strTemp = myStr
Debug.Print strTemp
Debug.Print strTemp
End Sub</lang>
End Sub</syntaxhighlight>
In a "standard" Module, the call should be :
In a "standard" Module, the call should be :
<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit


Sub test()
Sub test()
Line 1,874: Line 2,225:
Obj.Method_1
Obj.Method_1
Obj.Method_2
Obj.Method_2
End Sub</lang>
End Sub</syntaxhighlight>
{{out}}
{{out}}
<pre>Hello to you
<pre>Hello to you
Line 1,881: Line 2,232:
What is your name ?</pre>
What is your name ?</pre>


=={{header|V (Vlang)}}==
Vlang uses objects without classes (sometimes known as class-free or classless):


1) Structs can have methods assigned to them or be embedded in other structs.

2) Vlang also uses modules. Functions and structs can be exported from a module, which works somewhat similar to the class method.

<syntaxhighlight lang="Zig">
// Assigning methods to structs
struct HelloWorld {}

// Method's in Vlang are functions with special receiver arguments at the front (between fn and method name)
fn (sh HelloWorld) say_hello() {
println("Hello, world!")
}

fn (sb HelloWorld) say_bye() {
println("Goodbye, world!")
}

fn main() {

// instantiate object
hw := HelloWorld{}
// call methods of object
hw.say_hello()
hw.say_bye()
}
</syntaxhighlight>

{{out}}
<pre>
Hello, world!
Goodbye, world!
</pre>

Exporting functions from modules:

Create a module:
<syntaxhighlight lang="Zig">
// myfile.v
module mymodule

// Use "pub" to export a function
pub fn say_hi() {
println("hello from mymodule!")
}
</syntaxhighlight>

Import and use the module's function in your code:
<syntaxhighlight lang="Zig">
import mymodule

fn main() {
mymodule.say_hi()
}
</syntaxhighlight>

{{out}}
<pre>
hello from mymodule!
</pre>

=={{header|Wren}}==
Note that it's possible in Wren for instance and static methods in the same class to share the same name. This is because static methods are considered to belong to a separate meta-class.
<syntaxhighlight lang="wren>class MyClass {
construct new() {}
method() { System.print("instance method called") }
static method() { System.print("static method called") }
}

var mc = MyClass.new()
mc.method()
MyClass.method()</syntaxhighlight>

{{out}}
<pre>
instance method called
static method called
</pre>

=={{header|XBS}}==
You can call object methods using two types of structures. Classes and Objects.
===Classes===
<syntaxhighlight lang="xbs">class MyClass {
construct=func(self,Props){
self:Props=Props;
}{Props={}}
GetProp=func(self,Name){
send self.Props[Name];
}
}

set Class = new MyClass with [{Name="MyClass Name"}];
log(Class::GetProp("Name"));</syntaxhighlight>
{{out}}
<pre>
MyClass Name
</pre>
===Objects===
<syntaxhighlight lang="xbs">set MyObj = {
a=10;
AddA=func(self,x){
send self.a+x;
};
}

log(MyObj::AddA(2));</syntaxhighlight>
{{out}}
<pre>
12
</pre>
=={{header|XLISP}}==
=={{header|XLISP}}==
Class methods and instance methods are defined using <tt>DEFINE-CLASS-METHOD</tt> and <tt>DEFINE-METHOD</tt> respectively. They are called by sending a message to the class or to an instance of it: the message consists of (<i>a</i>) the name of the object that will receive it, which may be a class; (<i>b</i>) the name of the method, as a quoted symbol; and (<i>c</i>) the parameters if any.
Class methods and instance methods are defined using <tt>DEFINE-CLASS-METHOD</tt> and <tt>DEFINE-METHOD</tt> respectively. They are called by sending a message to the class or to an instance of it: the message consists of (<i>a</i>) the name of the object that will receive it, which may be a class; (<i>b</i>) the name of the method, as a quoted symbol; and (<i>c</i>) the parameters if any.
<lang xlisp>(DEFINE-CLASS MY-CLASS)
<syntaxhighlight lang="xlisp">(DEFINE-CLASS MY-CLASS)


(DEFINE-CLASS-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)
(DEFINE-CLASS-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)
Line 1,906: Line 2,369:
(DEFINE MY-INSTANCE (MY-CLASS 'NEW))
(DEFINE MY-INSTANCE (MY-CLASS 'NEW))


(MY-INSTANCE 'DO-SOMETHING-WITH 'BAR)</lang>
(MY-INSTANCE 'DO-SOMETHING-WITH 'BAR)</syntaxhighlight>
{{out}}
{{out}}
<pre>I am the class -- #<Class:MY-CLASS #x38994c8>
<pre>I am the class -- #<Class:MY-CLASS #x38994c8>
Line 1,912: Line 2,375:
I am an instance of the class -- #<Object:MY-CLASS #x39979d0>
I am an instance of the class -- #<Object:MY-CLASS #x39979d0>
You sent me the parameter BAR</pre>
You sent me the parameter BAR</pre>

=={{header|Zig}}==
=={{header|Zig}}==
Zig does not have classes nor objects. Zig's structs, however, can have methods; but they are not special. They are only namespaced functions that can be called with dot syntax.
Zig does not have classes nor objects. Zig's structs, however, can have methods; but they are not special. They are only namespaced functions that can be called with dot syntax.


<lang zig>const assert = @import("std").debug.assert;
<syntaxhighlight lang="zig">const testing = @import("std").testing;


pub const ID = struct {
pub const ID = struct {
Line 1,946: Line 2,408:
};
};


assert(person1.getAge() == 18);
// test getAge() method call
assert(ID.getAge(person2) == 20);
try testing.expectEqual(@as(u7, 18), person1.getAge());
try testing.expectEqual(@as(u7, 20), ID.getAge(person2));
}</lang>
}</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
In zkl, a class can be static (there will only exist one instance of the class). A function is always a member of some class but will only be static if it does not refer to instance data.
In zkl, a class can be static (there will only exist one instance of the class). A function is always a member of some class but will only be static if it does not refer to instance data.
<lang zkl>class C{var v; fcn f{v}}
<syntaxhighlight lang="zkl">class C{var v; fcn f{v}}
C.f() // call function f in class C
C.f() // call function f in class C
C.v=5; c2:=C(); // create new instance of C
C.v=5; c2:=C(); // create new instance of C
Line 1,962: Line 2,425:
D.f.isStatic //-->False
D.f.isStatic //-->False


class E{var v; fcn f{}} E.f.isStatic //-->True</lang>
class E{var v; fcn f{}} E.f.isStatic //-->True</syntaxhighlight>


<!-- Same omits as Classes page -->
<!-- Same omits as Classes page -->
{{omit from|360 Assembly}}
{{omit from|6502 Assembly}}
{{omit from|8051 Assembly}}
{{omit from|8080 Assembly}}
{{omit from|8086 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|AArch64 Assembly}}
{{omit from|ARM Assembly}}
{{omit from|AWK|not OO}}
{{omit from|AWK|not OO}}
{{omit from|BASIC|not OO}}
{{omit from|BASIC|not OO}}
Line 1,975: Line 2,446:
{{omit from|Maxima}}
{{omit from|Maxima}}
{{omit from|Metafont}}
{{omit from|Metafont}}
{{omit from|MIPS Assembly}}
{{omit from|Octave}}
{{omit from|Octave}}
{{omit from|PARI/GP}}
{{omit from|PARI/GP}}
{{omit from|Plain English|Plain English does not support objects.}}
{{omit from|Retro}}
{{omit from|Retro}}
{{omit from|REXX|not OO}}
{{omit from|REXX|not OO}}
{{omit from|Standard ML}}
{{omit from|TI-83 BASIC|not OO}}
{{omit from|TI-83 BASIC|not OO}}
{{omit from|TI-89 BASIC|Does not have user-defined types/classes}}
{{omit from|TI-89 BASIC|Does not have user-defined types/classes}}
{{omit from|UNIX Shell}}
{{omit from|UNIX Shell}}
{{omit from|Vim Script}}
{{omit from|Vim Script}}
{{omit from|x86 Assembly}}
{{omit from|Z80 Assembly}}
{{omit from|ZX Spectrum Basic|not OO}}
{{omit from|ZX Spectrum Basic|not OO}}

Latest revision as of 11:31, 12 November 2023

Task
Call an object method
You are encouraged to solve this task according to the task description, using any language you may know.

In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.

Show how to call a static or class method, and an instance method of a class.

ActionScript

// Static
MyClass.method(someParameter);

// Instance
myInstance.method(someParameter);

Ada

Ada is a language based on strict typing. Nevertheless, since Ada 95 (the first major revision of the language), Ada also includes the concepts of a class. Types may be tagged, and for each tagged type T there is an associated type T'Class. If you define a method as "procedure Primitive(Self: T)", the actual parameter Self must be of type T, exactly, and the method Primitive will be called, well, statically. This may be surprising, if you are used to other object-oriented languages.

If you define a method as "prodedure Dynamic(Self: T'Class)", the actual parameter can be either T or any of its descendents. Now, if you call Self.Primitive within the procedure Dynamic, it will be dispatching, i.e., it will call the primitive function matching the type of Self (i.e., either T or any of its subtype). This is what you would expect in many other object-oriented languages.

Finally, a static method can be defined as a subprogram within the same package that holds the object type and the other methods.

Specify the class My_Class, with one primitive subprogram, one dynamic subprogram and a static subprogram:

   package My_Class is
      type Object is tagged private;
      procedure Primitive(Self: Object); -- primitive subprogram
      procedure Dynamic(Self: Object'Class);
      procedure Static;
   private
      type Object is tagged null record;
   end My_Class;

Implement the package:

   package body My_Class is
      procedure Primitive(Self: Object) is
      begin
	 Put_Line("Hello World!");
      end Primitive;

      procedure Dynamic(Self: Object'Class) is
      begin
	 Put("Hi there! ... ");
	 Self.Primitive; -- dispatching call: calls different subprograms,
                         -- depending on the type of Self  
      end Dynamic;

      procedure Static is
      begin
	 Put_Line("Greetings");
      end Static;
   end My_Class;

Specify and implement a subclass of My_Class:

   package Other_Class is
      type Object is new My_Class.Object with null record;
      overriding procedure Primitive(Self: Object);
   end Other_Class;
   
   package body Other_Class is
      procedure Primitive(Self: Object) is
      begin
	 Put_Line("Hello Universe!");
      end Primitive;
   end Other_Class;

The main program, making the dynamic and static calls:

with Ada.Text_IO; use Ada.Text_IO;

procedure Call_Method is
   
   package My_Class is ... -- see above
   package body My_Class is ... -- see above
            
   package Other_Class is ... -- see above
   package body Other_Class is ... -- see above
   
   Ob1: My_Class.Object; -- our "root" type
   Ob2: Other_Class.Object; -- a type derived from the "root" type
      
begin
   My_Class.Static;
   Ob1.Primitive; 
   Ob2.Primitive; 
   Ob1.Dynamic; 
   Ob2.Dynamic;
end Call_Method;
Output:
Greetings
Hello World!
Hello Universe!
Hi there! ... Hello World!
Hi there! ... Hello Universe!

ALGOL 68

Algol 68 doesn't do OO as such, but it has structures, the members of which can be procedures. This allows OO features to be implemented, though without syntactic sugar, "this" pointers must be passed explicitly. In Algol 68, a OF b is used where most other languages would use b.a.
This means that a call to an instance method called "print" say of a class instance "a" in Algol 68 would be written ( print OF a )( a ), - note the explicit "this" parameter - whereas a.print would be used in most other languages.
Class methods could be members of the structure (as here) without a "this" parameter, or could be procedures defined outside the structure.
In this example, the instance and class methods return VOID, but this is not necessary, any return type could be used.

BEGIN # demonstrate a possible method of simulating class & instance methods  #
    # declare a "class"                                                       #
    MODE ANIMAL = STRUCT( STRING                 species
                        , PROC( REF ANIMAL )VOID print    # instance method   #
                        , PROC VOID              cm       # class method      #
                        );
    # constructor                                                             #
    PROC new animal = ( STRING species )REF REF ANIMAL:
         BEGIN
             HEAP ANIMAL     newv := ANIMAL( species
                                           , ( REF ANIMAL this )VOID:
                                               print( ( "[animal instance[", species OF this, "]]" ) )
                                           , VOID: print( ( "[animal class method called]" ) )
                                           );
             HEAP REF ANIMAL newa := newv;
             newa
         END # new animal # ;

    REF ANIMAL a
           := new animal( "PANTHERA TIGRIS" ); # create an instance of ANIMAL #
    cm OF a;                                   # call the class method        #
    ( print OF a )( a )                        # call the instance method     #
END
Output:
[animal class method called][animal instance[PANTHERA TIGRIS]]

Apex

// Static
MyClass.method(someParameter);

// Instance
myInstance.method(someParameter);

AutoHotkey

Works with: AutoHotkey_L

(AutoHotkey Basic does not have classes)

class myClass
{
	Method(someParameter){
		MsgBox % SomeParameter
	}
}

myClass.method("hi")
myInstance := new myClass
myInstance.Method("bye")

Bracmat

Bracmat has no classes. Rather, objects can be created as copies of other objects. In the example below, the variable MyObject has a copy of variable MyClass as value. Notice the extra level of reference in (MyObject..Method)$argument, comparable to MyObject->Method(argument) in C. Rather than being the object itself, MyObject points to an object and can be aliased by assigning to another variable.

Inside an object, the object is represented by its, comparable to this in other languages.

( ( myClass
  =   (name=aClass)
      ( Method
      = .out$(str$("Output from " !(its.name) ": " !arg))
      )
      (new=.!arg:?(its.name))
  )
& (myClass.Method)$"Example of calling a 'class' method"
& new$(myClass,object1):?MyObject
& (MyObject..Method)$"Example of calling an instance method"
& !MyObject:?Alias
& (Alias..Method)$"Example of calling an instance method from an alias"
);

Output:

Output from aClass: Example of calling a 'class' method
Output from object1: Example of calling an instance method
Output from object1: Example of calling an instance method from an alias


C

C has structures and it also has function pointers, which allows C structures to be associated with any function with the same signature as the pointer. Thus, C structures can also have object methods.

#include<stdlib.h>
#include<stdio.h>

typedef struct{
        int x;
        int (*funcPtr)(int);
}functionPair;

int factorial(int num){
        if(num==0||num==1)
                return 1;
        else
                return num*factorial(num-1);
}

int main(int argc,char** argv)
{
        functionPair response;

        if(argc!=2)
                return printf("Usage : %s <non negative integer>",argv[0]);
        else{
                response = (functionPair){.x = atoi(argv[1]),.funcPtr=&factorial};
                printf("\nFactorial of %d is %d\n",response.x,response.funcPtr(response.x));
        }
        return 0;
}

And yes, it works :

$ ./a.out 10

Factorial of 10 is 3628800

C++

// Static
MyClass::method(someParameter);

// Instance
myInstance.method(someParameter);

// Pointer
MyPointer->method(someParameter);

C_sharp

// Static
MyClass.Method(someParameter);
 
// Instance
myInstance.Method(someParameter);

ChucK

MyClass myClassObject;
myClassObject.myFunction(some parameter);

Clojure

(Long/toHexString 15) ; use forward slash for static methods
(System/currentTimeMillis)

(.equals 1 2)    ; use dot operator to call instance methods
(. 1 (equals 2)) ; alternative style

COBOL

Works with: COBOL 2002

There are two ways to invoke a method: the INVOKE statement and inline method invocation.

*> INVOKE statements.
INVOKE my-class "some-method"          *> Factory object
    USING BY REFERENCE some-parameter
    RETURNING foo
INVOKE my-instance "another-method"    *> Instance object
    USING BY REFERENCE some-parameter
    RETURNING foo

*> Inline method invocation.
MOVE my-class::"some-method"(some-parameter) TO foo       *> Factory object
MOVE my-instance::"another-method"(some-parameter) TO foo *> Instance object

To call factory methods of objects of an unknown type (such as when you may have a subclass of the class wanted), it is necessary to get a reference to the class's factory object by calling the "FactoryObject" method.

INVOKE some-instance "FactoryObject" RETURNING foo-factory
*> foo-factory can be treated like a normal object reference.
INVOKE foo-factory "someMethod"

CoffeeScript

While CoffeeScript does provide a useful class abstraction around its prototype-based inheritance, there aren't any actual classes.

class Foo
    @staticMethod: -> 'Bar'

    instanceMethod: -> 'Baz'

foo = new Foo

foo.instanceMethod() #=> 'Baz'
Foo.staticMethod() #=> 'Bar'


Common Lisp

In Common Lisp, classmethods are methods that apply to classes, rather than classes that contain methods.

(defclass my-class ()
  ((x
    :accessor get-x  ;; getter function
    :initarg :x      ;; arg name 
    :initform 0)))   ;; initial value

;; declaring a public class method
(defmethod square-x ((class-instance my-class))
  (* (get-x class-instance) (get-x class-instance)))

;; create an instance of my-class
(defvar *instance*
  (make-instance 'my-class :x 10))

(format t "Value of x: ~a~%" (get-x *instance*))

(format t "Value of x^2: ~a~%" (square-x *instance*))

Output (CLISP v2.49):

$ clisp object.cl
Value of x: 10
Value of x^2: 100


D

struct Cat {
    static int staticMethod() {
        return 2;
    }

    string dynamicMethod() { // Never virtual.
        return "Mew!";
    }
}

class Dog {
    static int staticMethod() {
        return 5;
    }

    string dynamicMethod() { // Virtual method.
        return "Woof!";
    }
}

void main() {
    // Static methods calls:
    assert(Cat.staticMethod() == 2);
    assert(Dog.staticMethod() == 5);

    Cat c; // This is a value on the stack.
    Dog d; // This is just a reference, set to null.

    // Other static method calls, discouraged:
    assert(c.staticMethod() == 2);
    assert(d.staticMethod() == 5);

    // Instance method calls:
    assert(c.dynamicMethod() == "Mew!");
    d = new Dog;
    assert(d.dynamicMethod() == "Woof!");
}

Delphi

Works with: Delphi version 6.0

This example shows the creation of a simple integer stack object. The object contains "Push" and "Pop" static methods.

{Simple stack interface}

type TSimpleStack = class(TObject)
 private
  FStack: array of integer;
 protected
 public
  procedure Push(I: integer);
  function Pop(var I: integer): boolean;
  constructor Create;
 end;


{ TSimpleStack implementation }

constructor TSimpleStack.Create;
{Initialize stack by setting size to zero}
begin
SetLength(FStack,0);
end;

function TSimpleStack.Pop(var I: integer): boolean;
{Pop top item off stack into "I" returns False if stack empty}
begin
Result:=Length(FStack)>=1;
if Result then
	begin
	{Get item from top of stack}
	I:=FStack[High(FStack)];
	{Delete the top item}
	SetLength(FStack,Length(FStack)-1);
	end;
end;

procedure TSimpleStack.Push(I: integer);
{Push item on stack by adding to end of array}
begin
{Increase stack size by one}
SetLength(FStack,Length(FStack)+1);
{Insert item}
FStack[High(FStack)]:=I;
end;


procedure ShowStaticMethodCall(Memo: TMemo);
var Stack: TSimpleStack;	{Declare stack object}
var I: integer;
begin
{Instanciate stack object}
Stack:=TSimpleStack.Create;
{Push items on stack by calling static method "Push"}
for I:=1 to 10 do Stack.Push(I);
{Call static method "Pop" to retrieve and display stack items}
while Stack.Pop(I) do
	begin
	Memo.Lines.Add(IntToStr(I));
	end;
{release stack memory and delete object}
Stack.Free;
end;
Output:
10
9
8
7
6
5
4
3
2
1
Elapsed Time: 10.571 ms.


Dragon

Making an object of class and then calling it.

r = new run()
r.val()

Dyalect

Dyalect supports both instance and static methods. Instance methods have a special this reference that returns an instance. Static method are always invoked through the type name.

//Static method on a built-in type Integer
static func Integer.Div(x, y) {
    x / y
}
 
//Instance method
func Integer.Div(n) {
    this / n
}
 
print(Integer.Div(12, 3))
print(12.Div(3))
Output:
4
4

E

This example is in need of improvement:

Add runnable example.

A method call in E has the syntax recipient.verb(arg1, arg2, ...), where recipient is an expression, verb is an identifier (or a string literal preceded by ::), and argN are expressions.

someObject.someMethod(someParameter)

In E, there are no distinguished "static methods". Instead, it is idiomatic to place methods on the maker of the object. This is very similar to methods on constructors in JavaScript, or class methods in Objective-C.

Ecstasy

Calling a method or function in Ecstasy follows roughly the same conventions as in Java and C#, but in order to prevent certain types of bugs, Ecstasy explicitly disallows calling a function as if it were a method.

module CallMethod {
    /**
     * This is a class with a method and a function.
     */
    const Example(String text) {
        @Override
        String toString() {                             // <-- this is a method
            return $"This is an example with text={text}";
        }

        static Int oneMoreThan(Int n) {                 // <-- this is a function
            return n+1;
        }
    }

    void run() {
        @Inject Console console;

        Example example      = new Example("hello!");
        String  methodResult = example.toString();      // <-- call a method
        console.print($"Result from calling a method: {methodResult.quoted()}");

     // Int funcResult = example.oneMoreThan(12);      // <-- compiler error
        Int funcResult = Example.oneMoreThan(12);      // <-- call a function
        console.print($"Results from calling a function: {funcResult}");

        // methods and functions are also objects that can be manipulated;
        // note that "function String()" === "Function<<>, <String>>"
        Method<Example, <>, <String>> method = Example.toString;
        function String() func   = method.bindTarget(example);
        console.print($"Calling a bound method: {func().quoted()}");

        // by default, a method with target T converts to a function taking a T;
        // Ecstasy refers to this as "Bjarning" (because C++ takes "this" as a param)
        val func2 = Example.toString;                   // <-- type: function String()
        console.print($"Calling a Bjarne'd function: {func2(example).quoted()}");

        // the function is just an object, and invocation (and in this case, binding,
        // as indicated by the '&' operator which requests a reference) is accomplished
        // using the "()" operator
        val func3 = Example.oneMoreThan;                // <-- type: function Int(Int)
        val func4 = &func3(13);                         // <-- type: function Int()
        console.print($"Calling a fully bound function: {func4()}");
    }
}
Output:
Result from calling a method: "This is an example with text=hello!"
Results from calling a function: 13
Calling a bound method: "This is an example with text=hello!"
Calling a Bjarne'd function: "This is an example with text=hello!"
Calling a fully bound function: 14

Elena

The message call:

    console.printLine("Hello"," ","World!");

Elixir

Elixir doesn't do objects. Instead of calling methods on object you send messages to processes. Here's an example of a process created with spawn_link which knows how to receive a message "concat" and return a result.

defmodule ObjectCall do
  def new() do
    spawn_link(fn -> loop end)
  end
  
  defp loop do
    receive do
      {:concat, {caller, [str1, str2]}} ->
        result = str1 <> str2
        send caller, {:ok, result}
        loop
    end
  end
  
  def concat(obj, str1, str2) do
    send obj, {:concat, {self(), [str1, str2]}}

    receive do
      {:ok, result} ->
        result
    end
  end
end

obj = ObjectCall.new()

IO.puts(obj |> ObjectCall.concat("Hello ", "World!"))

EMal

Translation of: Wren
type MyClass ^|we are defining a new data type and entering in its static context|^
fun method = void by block do writeLine("static method called") end
model ^|we enter the instance context|^
  fun method = void by block do writeLine("instance method called") end
end
type CallAnObjectMethod
var myInstance = MyClass() ^|creating an instance|^
myInstance.method()
MyClass.method()
Output:
instance method called
static method called

Factor

In Factor, there is no distinction between instance and static methods. Methods are contained in generic words and specialize on a class. Generic words define a method combination so methods know which object(s) to dispatch on. (But most methods dispatch on the object at the top of the data stack.) Under this object model, calling a method is no different than calling any other word.

USING: accessors io kernel literals math sequences ;
IN: rosetta-code.call-a-method

! Define some classes.
SINGLETON: dog
TUPLE: cat sassiness ;

! Define a constructor for cat.
C: <cat> cat

! Define a generic word that dispatches on the object at the top
! of the data stack.
GENERIC: speak ( obj -- )

! Define methods in speak which specialize on various classes.
M: dog speak drop "Woof!" print ;
M: cat speak sassiness>> 0.5 > "Hiss!" "Meow!" ? print ;
M: object speak drop "I don't know how to speak!" print ;

! Call speak on various objects.
! Despite being a method, it's called like any other word.
dog speak
0.75 <cat> speak
0.1 <cat> speak
"bird" speak
Output:
Woof!
Hiss!
Meow!
I don't know how to speak!

Forth

Works with: 4tH version 3.62.0
Translation of: D

There are numerous, mutually incompatible object oriented frameworks for Forth. This one works with the FOOS preprocessor extension of 4tH.

include lib/compare.4th
include 4pp/lib/foos.4pp

[ASSERT]                               \ enable assertions

:: Cat
   class
     method: dynamicCat                \ virtual method
   end-class {

    :static staticCat { 2 } ;          \ static method
    :method { s" Mew!" } ; defines dynamicCat
  }                                    \ for unrelated classes,
;                                      \ method names have to differ

:: Dog
   class
     method: dynamicDog                \ virtual method
   end-class {

    :static staticDog { 5 } ;
    :method { s" Woof!" } ; defines dynamicDog
  }                                    \ for unrelated classes,
;                                      \ method names have to differ

static Cat c                           \ create two static objects
static Dog d

: main
  assert( class -> staticCat 2 = )     \ check for valid method return
  assert( class -> staticDog 5 = )     \ of a static method

  assert( c -> staticCat 2 = )         \ check for valid method return
  assert( d -> staticDog 5 = )         \ of a static method

  assert( c => dynamicCat s" Mew!"  compare 0= )
  assert( d => dynamicDog s" Woof!" compare 0= )
;                                      \ same for dynamic methods

main

Works with any ANS Forth

Needs the FMS-SI (single inheritance) library code located here: http://soton.mpeforth.com/flag/fms/index.html

include FMS-SI.f

:class animal
  variable cnt 0 cnt ! \ static instance variable
  :m init: 1 cnt +! ;m
  :m cnt: cnt @ . ;m
;class

:class cat <super animal
  :m speak ." meow" ;m
;class

:class dog <super animal
  :m speak ." woof" ;m
;class

cat Frisky   \ instantiate a cat object named Frisky
dog Sparky   \ instantiate a dog object named Sparky

\ The class method cnt: will return the number of animals instantiated
\ regardless of which animal object is used.

\ The instance method speak will respond differently depending
\ on the class of the instance object.

Frisky cnt:  \ => 2 ok
Sparky cnt:  \ => 2 ok
Frisky speak \ => meow ok
Sparky speak \ => woof ok

Fortran

In modern Fortran a "derived type" concept corresponds to "class" in OOP. Such types have "type bound procedures", i.e. static methods. Procedure pointer components depend on the value of the object (so they are object-bound), can be redefined runtime and correspond approx to instances.

! type declaration
type my_type
 contains
procedure, pass :: method1
procedure, pass, pointer :: method2
end type my_type

! declare object of type my_type
type(my_type) :: mytype_object

!static call
 call mytype_object%method1() ! call method1 defined as subroutine
!instance?
 mytype_object%method2() ! call method2 defined as function

FreeBASIC

' FB 1.05.0 Win64

Type MyType
  Public:
    Declare Sub InstanceMethod(s As String)
    Declare Static Sub StaticMethod(s As String)
  Private:
    dummy_ As Integer ' types cannot be empty in FB
End Type

Sub MyType.InstanceMethod(s As String)
  Print s
End Sub

Static Sub MyType.StaticMethod(s As String)
  Print s
End Sub

Dim t As MyType
t.InstanceMethod("Hello world!")
MyType.Staticmethod("Hello static world!")
Print
Print "Press any key to quit the program"
Sleep
Output:
Hello world!
Hello static world!

FutureBasic

local fn FBClassDemo
  // Class
  ClassRef class = fn MutableStringClass
  // Cocoa base class name as human-readable string
  print fn StringFromClass( class )
  
  // Instantiate
  CFMutableStringRef mutStr = fn MutableStringNew
  
  // Method with single argument
  MutableStringSetString( mutStr, @"Hello, World!" )
  print mutStr
  
  // Method with multiple arguments
  MutableStringReplaceAllOccurrencesOfString( mutStr, @"World", @"Rosetta Code" )
  print mutStr
end fn

fn FBClassDemo

HandleEvents
Output:
NSMutableString
Hello, World!
Hello, Rosetta Code!

Go

Go distances itself from the word "object" and from many object oriented concepts. It does however have methods. Any user-defined type in Go can have methods and these work very much like "instance methods" of object oriented languages. The examples below illustrate details of Go methods and thus represent the concept of instance methods.

type Foo int // some custom type

// method on the type itself; can be called on that type or its pointer
func (self Foo) ValueMethod(x int) { }

// method on the pointer to the type; can be called on pointers
func (self *Foo) PointerMethod(x int) { }


var myValue Foo
var myPointer *Foo = new(Foo)

// Calling value method on value
myValue.ValueMethod(someParameter)
// Calling pointer method on pointer
myPointer.PointerMethod(someParameter)

// Value methods can always be called on pointers
// equivalent to (*myPointer).ValueMethod(someParameter)
myPointer.ValueMethod(someParameter)

// In a special case, pointer methods can be called on values that are addressable (i.e. lvalues)
// equivalent to (&myValue).PointerMethod(someParameter)
myValue.PointerMethod(someParameter)

// You can get the method out of the type as a function, and then explicitly call it on the object
Foo.ValueMethod(myValue, someParameter)
(*Foo).PointerMethod(myPointer, someParameter)
(*Foo).ValueMethod(myPointer, someParameter)

Go has no direct equivalent to class methods as long as you think of a Go type as a class. A Go package however can be organized and used much like a class, and in this context, any function exported from the package works much like a class method.

An example package:

package box

import "sync/atomic"

var sn uint32

type box struct {
    Contents string
    secret uint32
}

func New() (b *box) {
    b = &box{secret: atomic.AddUint32(&sn, 1)}
    switch sn {
    case 1:
        b.Contents = "rabbit"
    case 2:
        b.Contents = "rock"
    }
    return
}

func (b *box) TellSecret() uint32 {
    return b.secret
}

func Count() uint32 {
    return atomic.LoadUint32(&sn)
}

Example use:

package main

import "box"

func main() {
    // Call constructor.  Technically it's just an exported function,
    // but it's a Go idiom to naming a function New that serves the purpose
    // of a constructor.
    b := box.New() 

    // Call instance method.  In Go terms, simply a method.
    b.TellSecret()
    
    // Call class method.  In Go terms, another exported function.
    box.Count()
}

Icon and Unicon

Icon does not have objects or methods; they can be implemented on top of other types such as records.

Unicon has no concept of static methods; all methods are normally invoked using an instance of a class. While it is technically possible to call a method without an instance, it requires knowledge of the underlying implementation, such as the name-mangling conventions, and is non-standard.

procedure main()

   bar := foo()  # create instance
   bar.m2()      # call method m2 with self=bar, an implicit first parameter

   foo_m1( , "param1", "param2")  # equivalent of static class method, first (self) parameter is null
end

class foo(cp1,cp2)
   method m1(m1p1,m1p2)
      local ml1
      static ms1
      ml1 := m1p1
      # do something
      return
   end
   method m2(m2p1)
      # do something else
      return
   end
initially 
   L := [cp1]
end

Haskell

Haskell doesn't have objects in OOP sence (i.e. first-class sitizens appearing in runtime with incapsulated state and ability to send messages (methods) to other objects).

Haskell has first-class immutable records with fields of any type, representing abstraction and incapsulation (due to purity). Polymorphism is implemented via type-classes, which are similar to OOP interfaces.

Dummy example:

data Obj = Obj { field :: Int, method :: Int -> Int }

-- smart constructor
mkAdder :: Int -> Obj
mkAdder x = Obj x (+x) 

-- adding method from a type class
instanse Show Obj where
  show o = "Obj " ++ show (field o)
*Main> let o1 = Obj 1 (*5) 
*Main> field o1
1
*Main> method o1 6
30
*Main> show o1
Obj 1

*Main> let o2 = mkAdder 5
*Main> field o2
5
*Main> method o2 6
11
*Main> show o2
Obj 5

J

Note: In some languages "everything is an object". This is not the case in J. In J, non-trivial objects will contain arrays. This is a relatively deep issue, beyond the scope of this page, except that: method invocations are relatively rare, in J.

All method invocations must contain two underline characters in J:

Static:

methodName_className_ parameters

and, given an object instance reference:

objectReference=:'' conew 'className'

an instance invocation could be:

methodName__objectReference parameters

Note that J also supports infix notation when using methods. In this case, there will be a second parameter list, on the left of the method reference.

parameters methodName_className_ parameters

or

parameters methodName__objectReference parameters

These variations might be useful when building combining words that need to refer to two different kinds of things. But mostly it's to be consistent with the rest of the language.

Finally, note that static methods can be referred to using the same notation as instance methods -- in this case you must have a reference to the class name:

classReference=: <'className'
methodName__classReference parameters

This might be useful when you are working with a variety of classes which share a common structure.

You can also refer to a dynamic method in the same fashion that you use to refer to a instance method -- in this case you must know the object name (which is a number). For example, to refer to a method on object 123

methodName_123_ parameters

This last case can be useful when debugging.

Java

Static methods in Java are usually called by using the dot operator on a class name:

ClassWithStaticMethod.staticMethodName(argument1, argument2);//for methods with no arguments, use empty parentheses

Instance methods are called by using the dot operator on an instance:

ClassWithMethod varName = new ClassWithMethod();
varName.methodName(argument1, argument2);
//or
new ClassWithMethod().methodName(argument1, argument2);

Instance methods may not be called on references whose value is null (throws a NullPointerException).

Note: Static methods can also be called using the dot syntax on a reference to an instance, looking identical to an instance method call, but this is highly discouraged, and compilers usually complain about that (with a warning, not a failed compilation). The reason for this is that such a call is actually equivalent to a static method call on the static (compile-time) type of the reference in the source code. That means the runtime value of that reference is actually irrelevant, and the reference may be null or be a reference to an instance of a subclass, the compiler will still make it a call to the static method based on the class of the value at compile-time (i.e. inheritance does not apply; the method call is not resolved at runtime).

This means that there is no benefit to making a static method call this way, because one can make the call based on the static type that is already known from looking at the code when it is written. Furthermore, such a call may lead to serious pitfalls, leading one to believe that changing the object that it is called on could change the behavior. For example, a common snippet to sleep the thread for 1 second is the following: Thread.currentThread().sleep(1000);. However, since .sleep() is actually a static method, the compiler replaces it with Thread.sleep(1000); (since Thread.currentThread() has a return type of Thread). This makes it clear that the thread that is put to sleep is not under the user's control. However, written as Thread.currentThread().sleep(1000);, it may lead one to falsely believe it to be possible to sleep another thread by doing someOtherThread.sleep(1000); when in fact such a statement would also sleep the current thread.

JavaScript

If you have a object called x and a method called y then you can write:

x.y()

Julia

   module Animal
   abstract type Animal end
   abstract type Dog <: Animal end
   abstract type Cat <: Animal end

   struct Collie <: Dog
       name::String
       weight::Float64
   end
   struct Persian <: Cat
       name::String
       weight::Float64
   end
   #
   # This function is static: it works on any dog, even on a blank instance, in 
   #   the same way, to produce the same output for anything that isa Dog in type.
   #
   function soundalert(a::T) where T <: Dog
       println("Woof!")
   end
   #
   # This function depends on the class instance's data for its value, so this type
   #   of function is one way to do an instance method in Jula.
   #
   masskg(x) = x.weight

Kotlin

Kotlin does not have static methods, but they can be easily simulated by companion object methods.

class MyClass {
    fun instanceMethod(s: String) = println(s)

    companion object {
        fun staticMethod(s: String) = println(s)
    }
}

fun main() {
    val mc = MyClass()
    mc.instanceMethod("Hello instance world!")
    MyClass.staticMethod("Hello static world!")
}
Output:
Hello instance world!
Hello static world!

Latitude

In Latitude, everything is an object. Being prototype-oriented, Latitude does not distinguish between classes and instances. Calling a method on either a class or an instance is done by simple juxtaposition.

myObject someMethod (arg1, arg2, arg3).
MyClass someMethod (arg1, arg2, arg3).

The parentheses on the argument list may be omitted if there is at most one argument and the parse is unambiguous.

myObject someMethod "string constant argument".
myObject someMethod (argument). ;; Parentheses are necessary here
myObject someMethod. ;; No arguments

Finally, a colon may be used instead of parentheses, in which case the rest of the line is considered to be the argument list.

myObject someMethod: arg1, arg2, arg3.

LFE

LFE/Erlang doesn't have an object system. However, since LFE is a Lisp, one can do the same thing in LFE as one did in Lisps before CLOS: use closures to create and work with objects.

Not only that, but one may also use Erlang lightweight process to accomplish something very similar!

Examples for both approaches are given below.


With Closures

(defmodule aquarium
 (export all))

(defun fish-class (species)
  "
  This is the constructor that will be used most often, only requiring that
  one pass a 'species' string.

  When the children are not defined, simply use an empty list.
  "
  (fish-class species ()))

(defun fish-class (species children)
  "
  This contructor is mostly useful as a way of abstracting out the id
  generation from the larger constructor. Nothing else uses fish-class/2
  besides fish-class/1, so it's not strictly necessary.

  When the id isn't know, generate one.
  "
  (let* (((binary (id (size 128))) (: crypto rand_bytes 16))
         (formatted-id (car
                         (: io_lib format
                           '"~32.16.0b" (list id)))))
    (fish-class species children formatted-id)))

(defun fish-class (species children id)
  "
  This is the constructor used internally, once the children and fish id are
  known.
  "
  (let ((move-verb '"swam"))
    (lambda (method-name)
      (case method-name
        ('id
          (lambda (self) id))
        ('species
          (lambda (self) species))
        ('children
          (lambda (self) children))
        ('info
          (lambda (self)
            (: io format
              '"id: ~p~nspecies: ~p~nchildren: ~p~n"
              (list (get-id self)
                    (get-species self)
                    (get-children self)))))
        ('move
          (lambda (self distance)
            (: io format
              '"The ~s ~s ~p feet!~n"
              (list species move-verb distance))))
        ('reproduce
          (lambda (self)
            (let* ((child (fish-class species))
                   (child-id (get-id child))
                   (children-ids (: lists append
                                   (list children (list child-id))))
                   (parent-id (get-id self))
                   (parent (fish-class species children-ids parent-id)))
              (list parent child))))
        ('children-count
          (lambda (self)
            (: erlang length children)))))))

(defun get-method (object method-name)
  "
  This is a generic function, used to call into the given object (class
  instance).
  "
  (funcall object method-name))

; define object methods
(defun get-id (object)
  (funcall (get-method object 'id) object))

(defun get-species (object)
  (funcall (get-method object 'species) object))

(defun get-info (object)
  (funcall (get-method object 'info) object))

(defun move (object distance)
  (funcall (get-method object 'move) object distance))

(defun reproduce (object)
  (funcall (get-method object 'reproduce) object))

(defun get-children (object)
  (funcall (get-method object 'children) object))

(defun get-children-count (object)
  (funcall (get-method object 'children-count) object))

With this done, one can create objects and interact with them. Here is some usage from the LFE REPL:

; Load the file and create a fish-class instance:

> (slurp '"object.lfe")
#(ok object)
> (set mommy-fish (fish-class '"Carp"))
#Fun<lfe_eval.10.91765564>

; Execute some of the basic methods:

> (get-species mommy-fish)
"Carp"
> (move mommy-fish 17)
The Carp swam 17 feet!
ok
> (get-id mommy-fish)
"47eebe91a648f042fc3fb278df663de5"

; Now let's look at "modifying" state data (e.g., children counts):

> (get-children mommy-fish)
()
> (get-children-count mommy-fish)
0
> (set (mommy-fish baby-fish-1) (reproduce mommy-fish))
(#Fun<lfe_eval.10.91765564> #Fun<lfe_eval.10.91765564>)
> (get-id mommy-fish)
"47eebe91a648f042fc3fb278df663de5"
> (get-id baby-fish-1)
"fdcf35983bb496650e558a82e34c9935"
> (get-children-count mommy-fish)
1
> (set (mommy-fish baby-fish-2) (reproduce mommy-fish))
(#Fun<lfe_eval.10.91765564> #Fun<lfe_eval.10.91765564>)
> (get-id mommy-fish)
"47eebe91a648f042fc3fb278df663de5"
> (get-id baby-fish-2)
"3e64e5c20fb742dd88dac1032749c2fd"
> (get-children-count mommy-fish)
2
> (get-info mommy-fish)
id: "47eebe91a648f042fc3fb278df663de5"
species: "Carp"
children: ["fdcf35983bb496650e558a82e34c9935",
           "3e64e5c20fb742dd88dac1032749c2fd"]
ok

With Lightweight Processes

(defmodule object
 (export all))

(defun fish-class (species)
  "
  This is the constructor that will be used most often, only requiring that
  one pass a 'species' string.

  When the children are not defined, simply use an empty list.
  "
  (fish-class species ()))

(defun fish-class (species children)
  "
  This constructor is useful for two reasons: 
    1) as a way of abstracting out the id generation from the 
       larger constructor, and
    2) spawning the 'object loop' code (fish-class/3).
  "
  (let* (((binary (id (size 128))) (: crypto rand_bytes 16))
         (formatted-id (car
                         (: io_lib format
                           '"~32.16.0b" (list id)))))
    (spawn 'object
           'fish-class
           (list species children formatted-id))))

(defun fish-class (species children id)
  "
  This function is intended to be spawned as a separate process which is
  used to track the state of a fish. In particular, fish-class/2 spawns
  this function (which acts as a loop, pattern matching for messages).
  "
  (let ((move-verb '"swam"))
    (receive
      ((tuple caller 'move distance)
        (! caller (list species move-verb distance))
        (fish-class species children id))
      ((tuple caller 'species)
        (! caller species)
        (fish-class species children id))
      ((tuple caller 'children)
        (! caller children)
        (fish-class species children id))
      ((tuple caller 'children-count)
        (! caller (length children))
        (fish-class species children id))
      ((tuple caller 'id)
        (! caller id)
        (fish-class species children id))
      ((tuple caller 'info)
        (! caller (list id species children))
        (fish-class species children id))
      ((tuple caller 'reproduce)
        (let* ((child (fish-class species))
               (child-id (get-id child))
               (children-ids (: lists append
                               (list children (list child-id)))))
        (! caller child)
        (fish-class species children-ids id))))))

(defun call-method (object method-name)
  "
  This is a generic function, used to call into the given object (class
  instance).
  "
  (! object (tuple (self) method-name))
  (receive
    (data data)))

(defun call-method (object method-name arg)
  "
  Same as above, but with an additional argument.
  "
  (! object (tuple (self) method-name arg))
  (receive
    (data data)))

; define object methods
(defun get-id (object)
  (call-method object 'id))

(defun get-species (object)
  (call-method object 'species))

(defun get-info (object)
  (let ((data (call-method object 'info)))
    (: io format '"id: ~s~nspecies: ~s~nchildren: ~p~n" data)))

(defun move (object distance)
  (let ((data (call-method object 'move distance)))
    (: io format '"The ~s ~s ~p feet!~n" data)))

(defun reproduce (object)
  (call-method object 'reproduce))

(defun get-children (object)
  (call-method object 'children))

(defun get-children-count (object)
  (call-method object 'children-count))

Here is some usage from the LFE REPL:

; Load the file and create a fish-class instance:

> (slurp '"object.lfe")
#(ok object)
> (set mommy-fish (fish-class '"Carp"))
<0.33.0>

; Execute some of the basic methods:

> (get-species mommy-fish)
"Carp"
> (move mommy-fish 17)
The Carp swam 17 feet!
ok
> (get-id mommy-fish)
"47eebe91a648f042fc3fb278df663de5"

; Now let's look at modifying state data:

> (get-children mommy-fish)
()
> (get-children-count mommy-fish)
0
> (set baby-fish-1 (reproduce mommy-fish))
<0.34.0>
> (get-id mommy-fish)
"47eebe91a648f042fc3fb278df663de5"
> (get-id baby-fish-1)
"fdcf35983bb496650e558a82e34c9935"
> (get-children-count mommy-fish)
1
> (set baby-fish-2 (reproduce mommy-fish))
<0.35.0>
> (get-id mommy-fish)
"47eebe91a648f042fc3fb278df663de5"
> (get-id baby-fish-2)
"3e64e5c20fb742dd88dac1032749c2fd"
> (get-children-count mommy-fish)
2
> (get-info mommy-fish)
id: 47eebe91a648f042fc3fb278df663de5
species: Carp
children: ["fdcf35983bb496650e558a82e34c9935",
           "3e64e5c20fb742dd88dac1032749c2fd"]
ok

Lingo

-- call static method
script("MyClass").foo()

-- call instance method
obj = script("MyClass").new()
obj.foo()

Logtalk

In Logtalk, class or instance are roles that an object can play depending on the relations in other objects. Thus, a "class" can be defined by having an object specializing another object and an instance can be defined by having an object instantiating another object. Metaclasses are easily defined and thus a class method is just an instance method defined in the class metaclass.

% avoid infinite metaclass regression by
% making the metaclass an instance of itself
:- object(metaclass,
    instantiates(metaclass)).

    :- public(me/1).
    me(Me) :-
        self(Me).
 
:- end_object.
:- object(class,
    instantiates(metaclass)).

    :- public(my_class/1).
    my_class(Class) :-
        self(Self),
        instantiates_class(Self, Class).
 
:- end_object.
:- object(instance,
    instantiates(class)).

:- end_object.

Testing:

| ?- class::me(Me).
Me = class
yes

| ?- instance::my_class(Class).
Class = class
yes

Lua

Lua does not provide a specific OO implementation, but its metatable mechanism and sugar for method-like calls does make it easy to implement and use such as system, as evidenced by its multitude of class libraries in particular.

Instance methods, in their most basic form, are simply function calls where the calling object reference is duplicated and passed as the first argument. Lua offers some syntactical sugar to facilitate this, via the colon operator:

local object = { name = "foo", func = function (self) print(self.name) end }

object:func() -- with : sugar
object.func(object) -- without : sugar

Using metatables, and specifically the __index metamethod, it is possible to call a method stored in an entirely different table, while still passing the object used for the actual call:

local methods = { }
function methods:func () -- if a function is declared using :, it is given an implicit 'self' parameter
    print(self.name)
end

local object = setmetatable({ name = "foo" }, { __index = methods })

object:func() -- with : sugar
methods.func(object) -- without : sugar

Lua does not have a specific way of handling static methods, but similarly to Go, they could simply be implemented as regular functions inside of a module.

Example module, named box.lua:

local count = 0 
local box = { }
local boxmt = { __index = box }
function box:tellSecret ()
    return self.secret
end

local M = { }
function M.new () 
    count = count + 1
    return setmetatable({ secret = count, contents = count % 2 == 0 and "rabbit" or "rock" }, boxmt)
end
function M.count () 
    return count
end
return M

Example use:

local box = require 'box'

local b = box.new()

print(b:tellSecret())
print(box.count())

M2000 Interpreter

In M2000 there are some kinds of objects. Group is an object. We can compose members to groups, with functions, operators, modules, events, and inner groups, among other members of type pointer to object. Another type is the COM type. Here we see the Group object

Module CheckIt {
      \\ A class definition is a function which return a Group
      \\ We can make groups and we can alter them using Group statement
      \\ Groups may have other groups inside
      
      Group Alfa {
      Private:
            myvalue=100
      Public:
            Group SetValue {
                  Set (x) {
                        Link parent myvalue to m
                        m<=x
                  }
            }
            Module MyMethod {
                 Read x
                 Print x*.myvalue 
            }
      }
      
      Alfa.MyMethod 5 '500
      Alfa.MyMethod %x=200   ' 20000
      \\ we can copy Alfa to Z
      Z=Alfa
      Z.MyMethod 5
      Z.SetValue=300
      Z.MyMethod 5 ' 1500     
      Alfa.MyMethod 5    ' 500
      Dim A(10)
      A(3)=Z
      A(3).MyMethod 5 '1500
      A(3).SetValue=200
      A(3).MyMethod 5 '1000
      \\ get a pointer of group in A(3)
      k->A(3)
      k=>SetValue=100
      A(3).MyMethod 5 '500
      \\ k get pointer to Alfa
      k->Alfa
      k=>SetValue=500
      Alfa.MyMethod 5 '2500
      k->Z
      k=>MyMethod 5 ' 1500
      Z.SetValue=100
      k=>MyMethod 5 ' 500
}
Checkit

Maple

There is no real difference in how you call a static or instance method.

# Static
Method( obj, other, arg );
# Instance
Method( obj, other, arg );

MiniScript

MiniScript uses prototype-based inheritance, so the only difference between a static method and an instance method is in whether it uses the self pseudo-keyword.

Dog = {}
Dog.name = ""
Dog.help = function()
    print "This class represents dogs."
end function
Dog.speak = function()
    print self.name + " says Woof!"
end function

fido = new Dog
fido.name = "Fido"

Dog.help    // calling a "class method"
fido.speak  // calling an "instance method"
Output:
This class represents dogs.
Fido says Woof!

Nanoquery

class MyClass
	declare static id = 5
	declare MyName

	// constructor
	def MyClass(MyName)
		this.MyName = MyName
	end

	// class method
	def getName()
		return this.MyName
	end

	// static method
	def static getID()
		return id
	end
end

// call the static method
println MyClass.getID()

// instantiate a new MyClass object with the name "test"
// and call the class method
myclass = new(MyClass, "test")
println myclass.getName()
Output:
5
test

Nemerle

// Static
MyClass.Method(someParameter);
 
// Instance
myInstance.Method(someParameter);

NetRexx

Like Java, static methods in NetRexx are called by using the dot operator on a class name:

SomeClass.staticMethod()

Instance methods are called by using the dot operator on an instance:

objectInstance = SomeClass() -- create a new instance of the class
objectInstance.instanceMethod() -- call the instance method

SomeClass().instanceMethod() -- same as above; create a new instance of the class and call the instance method immediately

Nim

In Nim there are no object methods, but regular procedures can be called with method call syntax:

var x = @[1, 2, 3]
add(x, 4)
x.add(5)

OASYS Assembler

The OASYS runtime is strange; all classes share the same methods and properties, there are no static methods and properties, and there are no procedures/functions other than methods on objects. However, the initialization method can be called on a null object (no other method has this possibility).

The following code calls a method called &GO on the current object:

+&GO

Objeck

ClassName->some_function(); # call class function
instance->some_method(); # call instance method

Objeck uses the same syntax for instance and class method calls. In Objeck, functions are the equivalent of public static methods.

Object Pascal

Object Pascal as implemented in Delphi and Free Pascal supports both static (known in Pascal as class method) and instance methods. Free Pascal has two levels of static methods, one using the class keyword and one using both the class and the static keywords. A class method can be called in Pascal, while a static class method could be called even from C, that's the main difference.

// Static (known in Pascal as class method)
MyClass.method(someParameter);

// Instance
myInstance.method(someParameter);

Objective-C

In Objective-C, calling an instance method is sending a message to an instance, and calling a class method is sending a message to a class object. Class methods are inherited through inheritance of classes. All messages (whether sent to a normal object or class object) are resolved dynamically at runtime, hence there are no "static" methods (see also: Smalltalk).

// Class
[MyClass method:someParameter];
// or equivalently:
id foo = [MyClass class];
[foo method:someParameter];

// Instance
[myInstance method:someParameter];

// Method with multiple arguments
[myInstance methodWithRed:arg1 green:arg2 blue:arg3];

// Method with no arguments
[myInstance method];

OCaml

We can only call the method of an instantiated object:

my_obj#my_meth params

Oforth

When a method is called, the top of the stack is used as the object on which the method will be applyed :

1.2 sqrt

For class methods, the top of the stack must be a class (which is also an object of Class class) :

Date now

ooRexx

say "pi:" .circle~pi
c=.circle~new(1)
say "c~area:" c~area
Do r=2 To 10
 c.r=.circle~new(r)
 End
say .circle~instances('') 'circles were created'

::class circle
::method pi class -- a class method
  return 3.14159265358979323

::method instances class -- another class method
  expose in
  use arg a
  If datatype(in)<>'NUM' Then in=0
  If a<>'' Then
    in+=1
  Return in

::method init
  expose radius
  use arg radius
  self~class~instances('x')

::method area     -- an instance method
  expose radius
  Say self~class
  Say self
  return self~class~pi * radius * radius

Output:

pi: 3.14159265358979323
The CIRCLE class
a CIRCLE
c~area: 3.14159265
10 circles were created

Perl

# Class method
MyClass->classMethod($someParameter);
# Equivalently using a class name
my $foo = 'MyClass';
$foo->classMethod($someParameter);


# Instance method
$myInstance->method($someParameter);

# Calling a method with no parameters
$myInstance->anotherMethod;

# Class and instance method calls are made behind the scenes by getting the function from
# the package and calling it on the class name or object reference explicitly
MyClass::classMethod('MyClass', $someParameter);
MyClass::method($myInstance, $someParameter);

Phix

Library: Phix/Class

Class methods are only "static" (not really a Phix term) if you don't override them.
Phix does not demand that all routines be inside classes; traditional standalone routines are "static" in every sense.
There is no way to call a class method without an instance, since "this" will typecheck even if not otherwise used.

without js -- (no class in p2js)
class test
    string msg = "this is a test"
    procedure show() ?this.msg end procedure
    procedure inst() ?"this is dynamic" end procedure
end class
test t = new()
t.show()            -- prints "this is a test"
t.inst()            -- prints "this is dynamic"
t.inst = t.show
t.inst()            -- prints "this is a test"

PHP

// Static method
MyClass::method($someParameter);
// In PHP 5.3+, static method can be called on a string of the class name
$foo = 'MyClass';
$foo::method($someParameter);


// Instance method
$myInstance->method($someParameter);

PicoLisp

Method invocation is syntactically equivalent to normal function calls. Method names have a trailing '>' by convention.

(foo> MyClass)
(foo> MyObject)

Pike

Pike does not have static methods. (the static modifier in Pike is similar to protected in C++).

regular methods can be called in these ways:

obj->method();
obj["method"]();
call_function(obj->method);
call_function(obj["method"]);

call_function() is rarely used anymore.

because () is actually an operator that is applied to a function reference, the following is also possible:

function func = obj->method;
func();

as alternative to static function, modules are used. a module is essentially a static class. a function in a module can be called like this:

module.func();
module["func"]();

it should be noted that module.func is resolved at compile time while module["func"] is resolved at runtime.

PL/SQL

create or replace TYPE myClass AS OBJECT (
    -- A class needs at least one member even though we don't use it
    dummy NUMBER,
    STATIC FUNCTION static_method RETURN VARCHAR2,
    MEMBER FUNCTION instance_method RETURN VARCHAR2
);
/
CREATE OR REPLACE TYPE BODY myClass AS
    STATIC FUNCTION static_method RETURN VARCHAR2 IS
    BEGIN
        RETURN 'Called myClass.static_method';
    END static_method;
    
    MEMBER FUNCTION instance_method RETURN VARCHAR2 IS
    BEGIN
        RETURN 'Called myClass.instance_method';
    END instance_method;
END;
/

DECLARE
    myInstance myClass;
BEGIN
    myInstance := myClass(null);
    DBMS_OUTPUT.put_line( myClass.static_method() );
    DBMS_OUTPUT.put_line( myInstance.instance_method() );
END;/

PowerShell

$Date = Get-Date
$Date.AddDays( 1 )
[System.Math]::Sqrt( 2 )

Processing

// define a rudimentary class
class HelloWorld
{
    public static void sayHello()
    {
        println("Hello, world!");
    }
    public void sayGoodbye()
    {
        println("Goodbye, cruel world!");
    }
}

// call the class method
HelloWorld.sayHello();

// create an instance of the class
HelloWorld hello = new HelloWorld();

// and call the instance method
hello.sayGoodbye();

Python

class MyClass(object):
	@classmethod
	def myClassMethod(self, x):
		pass
	@staticmethod
	def myStaticMethod(x):
		pass
	def myMethod(self, x):
		return 42 + x

myInstance = MyClass()

# Instance method
myInstance.myMethod(someParameter)
# A method can also be retrieved as an attribute from the class, and then explicitly called on an instance:
MyClass.myMethod(myInstance, someParameter)


# Class or static methods
MyClass.myClassMethod(someParameter)
MyClass.myStaticMethod(someParameter)
# You can also call class or static methods on an instance, which will simply call it on the instance's class
myInstance.myClassMethod(someParameter)
myInstance.myStaticMethod(someParameter)

Quackery

Quackery is not an Object Oriented language. However it is possible to create a zen-like "distilled essence of object-orientation" in just a few lines of code.

Note that Quackery also does not have operator overloading (but see Modular arithmetic#Quackery for an illustration of how this can be achieved) so there is limited inheritance of methods possible - here only the methods localise and delocalise are common to all object types.

(It would be possible to extend this technique to a more fully-fledged object oriented system. See Dick Pountain's slim volume "Object Oriented FORTH: Implementation of Data Structures" (pub. 1987) for an example of doing so in Forth; a language to which Quackery is related, but slightly less amenable to such shenanigans.)

( ---------------- zen object orientation -------------- )
 
[ immovable 
  ]this[ swap do ]done[ ] is object            (   -->   )
 
[ ]'[ ]                   is method            (   --> [ )
 
[ method 
    [ dup share
      swap put ] ]        is localise          (   --> [ )
 
[ method [ release ] ]    is delocalise        (   --> [ )
 
 
( -------------- example: counter methods -------------- )

( to create a counter object, use: 
           "[ object 0 ]  is 'name' ( [ -->   )"         )
  
[ method 
    [ 0 swap replace ] ]  is reset-counter     (   --> [ )
 
[ method  
    [ 1 swap tally ] ]    is increment-counter (   --> [ )
 
[ method [ share ] ]      is report-counter    (   --> [ )
 
 
( -------------------- demonstration ------------------- )
 
say 'Creating counter object: "mycounter".' cr cr 
[ object 0 ]              is mycounter         ( [ -->   )
 
say "Initial value of mycounter: "
report-counter mycounter echo cr cr
 
say "Incrementing mycounter three times." cr
3 times [ increment-counter mycounter ]
 
say "Current value of mycounter: "
report-counter mycounter echo cr cr
 
say "Localising mycounter." cr cr
localise mycounter
 
say "    Current value of mycounter: "
report-counter mycounter echo cr cr
 
say "    Resetting mycounter." cr
reset-counter mycounter
 
say "    Current value of mycounter: "
report-counter mycounter echo cr cr
 
say "    Incrementing mycounter six times." cr
6 times [ increment-counter mycounter ]
 
say "    Current value of mycounter: "
report-counter mycounter echo cr cr
 
say "Delocalising mycounter." cr cr
delocalise mycounter
 
say "Current value of mycounter: "
report-counter mycounter echo cr cr
 
say "Resetting mycounter." cr
reset-counter mycounter
 
say "Current value of mycounter: "
report-counter mycounter echo cr cr
Output:
Creating counter object: "mycounter".

Initial value of mycounter: 0

Incrementing mycounter three times.
Current value of mycounter: 3

Localising mycounter.

    Current value of mycounter: 3

    Resetting mycounter.
    Current value of mycounter: 0

    Incrementing mycounter six times.
    Current value of mycounter: 6

Delocalising mycounter.

Current value of mycounter: 3

Resetting mycounter.
Current value of mycounter: 0

Racket

The following snippet shows a call to the start method of the timer% class.

#lang racket/gui

(define timer (new timer%))
(send timer start 100)

Raku

(formerly Perl 6)

Works with: Rakudo version 2015.12

Basic method calls

class Thing { 
  method regular-example() { say 'I haz a method' }

  multi method multi-example() { say 'No arguments given' }
  multi method multi-example(Str $foo) { say 'String given' }
  multi method multi-example(Int $foo) { say 'Integer given' }
};

# 'new' is actually a method, not a special keyword:
my $thing = Thing.new;

# No arguments: parentheses are optional
$thing.regular-example;
$thing.regular-example();
$thing.multi-example;
$thing.multi-example();

# Arguments: parentheses or colon required
$thing.multi-example("This is a string");
$thing.multi-example: "This is a string";
$thing.multi-example(42);
$thing.multi-example: 42;

# Indirect (reverse order) method call syntax: colon required
my $foo = new Thing: ;
multi-example $thing: 42;

Meta-operators

The . operator can be decorated with meta-operators.

my @array = <a z c d y>;
@array .= sort;  # short for @array = @array.sort;

say @array».uc;  # uppercase all the strings: A C D Y Z

Classless methods

A method that is not in a class can be called by using the & sigil explicitly.

my $object = "a string";  # Everything is an object.
my method example-method {
    return "This is { self }.";
}

say $object.&example-method;  # Outputs "This is a string."

Ring

new point { print() }
Class Point
        x = 10  y = 20  z = 30
        func print see x + nl + y + nl + z + nl
o1 = new System.output.console
o1.print("Hello World")

Package System.Output
        Class Console
                Func Print cText
                        see cText + nl

Ruby

# Class method
MyClass.some_method(some_parameter)

# Class may be computed at runtime
foo = MyClass
foo.some_method(some_parameter)


# Instance method
my_instance.a_method(some_parameter)

# The parentheses are optional
my_instance.a_method some_parameter

# Calling a method with no parameters
my_instance.another_method

Rust

struct Foo;

impl Foo {
    // implementation of an instance method for struct Foo
    // returning the answer to life
    fn get_the_answer_to_life(&self) -> i32 {
        42
    }

    // implementation of a static method for struct Foo
    // returning a new instance object
    fn new() -> Foo {
        println!("Hello, world!");
        Foo // returning the new Foo object
    }
}

fn main() {
    // create the instance object foo,
    // by calling the static method new of struct Foo
    let foo = Foo::new();

    // get the answer to life 
    // by calling the instance method of object foo
    println!("The answer to life is {}.", foo.get_the_answer_to_life());
    
    // Note that in Rust, methods still work on references to the object.
    // Rust will automatically do the appropriate dereferencing to get the method to work:
    let lots_of_references = &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&foo;
    println!("The answer to life is still {}." lots_of_references.get_the_answer_to_life());
}

Scala

/* This class implicitly includes a constructor which accepts an Int and
 *  creates "val variable1: Int" with that value.
 */
class MyClass(val memberVal: Int) { // Acts like a getter, getter automatically generated.
  var variable2 = "asdf" // Another instance variable; a public mutable this time
  def this() = this(0) // An auxilliary constructor that instantiates with a default value
}

object HelloObject {
  val s = "Hello" // Not private, so getter auto-generated
}

/** Demonstrate use of our example class.
 */
object Call_an_object_method extends App {
  val s = "Hello"
  val m = new MyClass
  val n = new MyClass(3)

  assert(HelloObject.s == "Hello") // "Hello" by object getterHelloObject
  assert(m.memberVal == 0)
  assert(n.memberVal == 3)
  println("Successfully completed without error.")
}

Sidef

class MyClass {
    method foo(arg) { say arg }
}

var arg = 42;

# Call a class method
MyClass.foo(arg);

# Alternatively, using an expression for the method name
MyClass.(:foo)(arg);

# Create an instance
var instance = MyClass();

# Instance method
instance.foo(arg);

# Alternatively, by using an expression for the method name
instance.(:foo)(arg);

# Alternatively, by asking for a method
instance.method(:foo)(arg);

Smalltalk

In Smalltalk, calling an instance method is sending a message to an instance, and calling a class method is sending a message to a class object. Class methods are inherited through inheritance of classes. All messages (whether sent to a normal object or class object) are resolved dynamically at runtime, hence strictly speaking, there are no "static" methods. Often in literature, Smalltalk's class messages are described as synonymous to static function calls. This is wrong, because class methods can be overwritten in subclasses just as any other message. Classes are first class objects, meaning that references to them can be passed as argument, stored in other objects or returned as the result of a message send. This makes some of the common design patterns which deal with creation of objects trivial or even superfluous. (see also: ObjectiveC)

" Class "
MyClass selector: someArgument .
" or equivalently "
foo := MyClass .
foo selector: someArgument.

" Instance "
myInstance selector: someArgument.

" Message with multiple arguments "
myInstance fooWithRed:arg1 green:arg2 blue:arg3 .

" Message with no arguments "
myInstance selector.

" Binary (operator) message"
myInstance + argument .


Example for dynamic class determination:

theCar := (someCondition ifTrue:[ Ford ] ifFalse: [ Jaguar ]) new.

Message names (selectors) can be chosen or constructed dynamically at runtime. For example:

whichMessage := #( #'red' #'green' #'blue') at: computedIndex.
foo perform: whichMessage

or:

theMessage := ('handleFileType' , suffix) asSymbol.
foo perform: theMessage.

This is often sometimes used as a dispatch mechanism (also, to implement state machines, for example).

Of course, especially with all that dynamics, a selector for an unimplemented message might be encountered. This raises a MessageNotUnderstood exception (runtime exception).

[
    foo perform: theMessage
] on: MessageNotUnderstood do:[
   Dialog information: 'sorry'
]

SuperCollider

In SuperCollider, classes are objects. To call a class or object method, a message is passed to the class or the object instance. In the implementation, class method names are prefixed with an asterix, all other methods are instance methods.

	SomeClass {
	
		*someClassMethod {
			
		}
		
		someInstanceMethod {
			
		}
		
	}
	
	SomeClass.someClassMethod;
	
	a = SomeClass.new;
	a.someInstanceMethod;

Swift

In Swift, instance methods can be declared on structs, enums, and classes. "Type methods", which include static methods for structs and enums, and class methods for classes, can be called on the type. Class methods are inherited through inheritance of classes, and are resolved dynamically at runtime like instance methods. (see also: Smalltalk).

// Class
MyClass.method(someParameter)
// or equivalently:
let foo = MyClass.self
foo.method(someParameter)

// Instance
myInstance.method(someParameter)

// Method with multiple arguments
myInstance.method(red:arg1, green:arg2, blue:arg3)

Tcl

package require Tcl 8.6
# "Static" (on class object)
MyClass mthd someParameter

# Instance
$myInstance mthd someParameter

TXR

TXR Lisp method invocation syntax is obj.(method args...).

Static methods are just functions that don't take an object as an argument. The above notation, therefore, normally isn't used, rather the functional square brackets: [obj.function args...].

The defstruct clause :method is equivalent to :function except that it requires at least one argument, the leftmost one denoting the object.

The obj.(method args...) could be used to call a static function; it would pass obj as the leftmost argument. Vice versa, the square bracket call notation can be used to invoke a method; the object has to be manually inserted: [obj.function obj args...].

(defvarl thing-count 0)

(defstruct thing ()
  (call-count 0)

  (:init (me)
    (inc thing-count))
  (:function get-thing-count () thing-count)
  (:method get-call-count (me) (inc me.call-count)))

(let ((t1 (new thing))
      (t2 (new thing)))
  (prinl t1.(get-call-count)) ;; prints 1
  (prinl t1.(get-call-count)) ;; prints 2
  (prinl t1.(get-call-count)) ;; prints 3
  (prinl t2.(get-call-count)) ;; prints 1
  (prinl t2.(get-call-count)) ;; prints 2
  (prinl t2.(get-call-count)) ;; prints 3
  
  (prinl [t1.get-thing-count])  ;; prints 2
  (prinl [t2.get-thing-count])) ;; prints 2
Output:
1
2
3
1
2
3
2
2

Ursa

# create an instance of the built-in file class
decl file f

# call the file.open method
f.open "filename.txt"

VBA

First we have to create a class module named "myObject" :

Option Explicit

Sub Method_1(Optional myStr As String)
Dim strTemp As String
    If myStr <> "" Then strTemp = myStr
    Debug.Print strTemp
End Sub

Static Sub Method_2(Optional myStr As String)
Dim strTemp As String
    If myStr <> "" Then strTemp = myStr
    Debug.Print strTemp
End Sub

In a "standard" Module, the call should be :

Option Explicit

Sub test()
Dim Obj As New myObject
    Obj.Method_1 "Hello to you"
    Obj.Method_2 "What is your name ?"
    Obj.Method_1
    Obj.Method_2
End Sub
Output:
Hello to you
What is your name ?

What is your name ?

V (Vlang)

Vlang uses objects without classes (sometimes known as class-free or classless):

1) Structs can have methods assigned to them or be embedded in other structs.

2) Vlang also uses modules. Functions and structs can be exported from a module, which works somewhat similar to the class method.

// Assigning methods to structs
struct HelloWorld {}

// Method's in Vlang are functions with special receiver arguments at the front (between fn and method name)
fn (sh HelloWorld) say_hello() {
	 println("Hello, world!")
}

fn (sb HelloWorld) say_bye() {
	 println("Goodbye, world!")
}

fn main() {

	//  instantiate object
	hw := HelloWorld{}
	
	// call methods of object
	hw.say_hello()
	hw.say_bye()
}
Output:
Hello, world!
Goodbye, world!

Exporting functions from modules:

Create a module:

// myfile.v
module mymodule

// Use "pub" to export a function
pub fn say_hi() {
	println("hello from mymodule!")
}

Import and use the module's function in your code:

import mymodule

fn main() {
	mymodule.say_hi()
}
Output:
hello from mymodule!

Wren

Note that it's possible in Wren for instance and static methods in the same class to share the same name. This is because static methods are considered to belong to a separate meta-class.

class MyClass {
    construct new() {}
    method() { System.print("instance method called") }
    static method() { System.print("static method called") }
}

var mc = MyClass.new()
mc.method()
MyClass.method()
Output:
instance method called
static method called

XBS

You can call object methods using two types of structures. Classes and Objects.

Classes

class MyClass {
	construct=func(self,Props){
		self:Props=Props;
	}{Props={}}
	GetProp=func(self,Name){
		send self.Props[Name];
	}
}

set Class = new MyClass with [{Name="MyClass Name"}];
log(Class::GetProp("Name"));
Output:
MyClass Name

Objects

set MyObj = {
	a=10;
	AddA=func(self,x){
		send self.a+x;
	};
}

log(MyObj::AddA(2));
Output:
12

XLISP

Class methods and instance methods are defined using DEFINE-CLASS-METHOD and DEFINE-METHOD respectively. They are called by sending a message to the class or to an instance of it: the message consists of (a) the name of the object that will receive it, which may be a class; (b) the name of the method, as a quoted symbol; and (c) the parameters if any.

(DEFINE-CLASS MY-CLASS)

(DEFINE-CLASS-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)
    (DISPLAY "I am the class -- ")
    (DISPLAY SELF)
    (NEWLINE)
    (DISPLAY "You sent me the parameter ")
    (DISPLAY SOME-PARAMETER)
    (NEWLINE))

(DEFINE-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)
    (DISPLAY "I am an instance of the class --  ")
    (DISPLAY SELF)
    (NEWLINE)
    (DISPLAY "You sent me the parameter ")
    (DISPLAY SOME-PARAMETER)
    (NEWLINE))

(MY-CLASS 'DO-SOMETHING-WITH 'FOO)

(DEFINE MY-INSTANCE (MY-CLASS 'NEW))

(MY-INSTANCE 'DO-SOMETHING-WITH 'BAR)
Output:
I am the class -- #<Class:MY-CLASS #x38994c8>
You sent me the parameter FOO
I am an instance of the class --  #<Object:MY-CLASS #x39979d0>
You sent me the parameter BAR

Zig

Zig does not have classes nor objects. Zig's structs, however, can have methods; but they are not special. They are only namespaced functions that can be called with dot syntax.

const testing = @import("std").testing;

pub const ID = struct {
    name: []const u8,
    age: u7,

    const Self = @This();

    pub fn init(name: []const u8, age: u7) Self {
        return Self{
            .name = name,
            .age = age,
        };
    }

    pub fn getAge(self: Self) u7 {
        return self.age;
    }
};

test "call an object method" {
    // Declare an instance of a struct by using a struct method.
    const person1 = ID.init("Alice", 18);

    // Or by declaring it manually.
    const person2 = ID{
        .name = "Bob",
        .age = 20,
    };

    // test getAge() method call
    try testing.expectEqual(@as(u7, 18), person1.getAge());
    try testing.expectEqual(@as(u7, 20), ID.getAge(person2));
}

zkl

In zkl, a class can be static (there will only exist one instance of the class). A function is always a member of some class but will only be static if it does not refer to instance data.

class C{var v; fcn f{v}}
C.f() // call function f in class C
C.v=5; c2:=C();    // create new instance of C
println(C.f()," ",c2.f()) //-->5 Void
C.f.isStatic //--> False

class [static] D{var v=123; fcn f{v}}
D.f(); D().f(); // both return 123
D.f.isStatic //-->False

class E{var v; fcn f{}} E.f.isStatic //-->True