Call an object method: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (sntax highlighting fixup automation)
m (→‎{{header|Wren}}: Changed to Wren S/H)
(23 intermediate revisions by 13 users not shown)
Line 1:
{{task|Basic language learning}}
[[Category:Object oriented]]
[[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.
 
Show how to call a static or class method, and an instance method of a class.
 
=={{header|ActionScript}}==
<syntaxhighlight lang="actionscript">// Static
MyClass.method(someParameter);
 
// Instance
myInstance.method(someParameter);</syntaxhighlight>
 
=={{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.
Line 22 ⟶ 20:
 
Specify the class My_Class, with one primitive subprogram, one dynamic subprogram and a static subprogram:
<syntaxhighlight lang=Ada"ada"> package My_Class is
type Object is tagged private;
procedure Primitive(Self: Object); -- primitive subprogram
Line 32 ⟶ 30:
 
Implement the package:
<syntaxhighlight lang=Ada"ada"> package body My_Class is
procedure Primitive(Self: Object) is
begin
Line 52 ⟶ 50:
 
Specify and implement a subclass of My_Class:
<syntaxhighlight lang=Ada"ada"> package Other_Class is
type Object is new My_Class.Object with null record;
overriding procedure Primitive(Self: Object);
Line 66 ⟶ 64:
The main program, making the dynamic and static calls:
 
<syntaxhighlight lang=Ada"ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Call_Method is
Line 94 ⟶ 92:
Hi there! ... Hello World!
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}}==
<syntaxhighlight lang=Java"java">// Static
MyClass.method(someParameter);
 
Line 105 ⟶ 140:
{{works with|AutoHotkey_L}}
(AutoHotkey Basic does not have classes)
<syntaxhighlight lang=AHK"ahk">class myClass
{
Method(someParameter){
Line 115 ⟶ 150:
myInstance := new myClass
myInstance.Method("bye")</syntaxhighlight>
 
=={{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.
 
Inside an object, the object is represented by <code>its</code>, comparable to <code>this</code> in other languages.
<syntaxhighlight lang="bracmat">( ( myClass
= (name=aClass)
( Method
Line 137 ⟶ 171:
Output from object1: Example of calling an instance method
Output from object1: Example of calling an instance method from an alias</pre>
 
 
=={{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.
<syntaxhighlight lang=C"c">
#include<stdlib.h>
#include<stdio.h>
Line 175 ⟶ 210:
Factorial of 10 is 3628800
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">// Static
MyClass::method(someParameter);
 
Line 186 ⟶ 220:
MyPointer->method(someParameter);
</syntaxhighlight>
 
=={{header|C_sharp|C#}}==
<syntaxhighlight lang="csharp">// Static
MyClass.Method(someParameter);
// Instance
myInstance.Method(someParameter);</syntaxhighlight>
 
=={{header|ChucK}}==
<syntaxhighlight lang="c">
MyClass myClassObject;
myClassObject.myFunction(some parameter);
</syntaxhighlight>
 
=={{header|Clojure}}==
<syntaxhighlight lang="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</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang=cobol>*> INVOKE
<syntaxhighlight lang="cobolfree">*> INVOKE statements.
INVOKE FooClass "someMethod" RETURNING bar *> Factory object
INVOKE foomy-instanceclass "anotherMethodsome-method" RETURNING bar *> InstanceFactory 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 FooClassmy-class::"someMethodsome-method"(some-parameter) TO bar foo *> Factory object
MOVE foomy-instance::"anotherMethodanother-method"(some-parameter) TO barfoo *> 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.
<syntaxhighlight lang=cobol"cobolfree">INVOKE foosome-instance "FactoryObject" RETURNING foo-factory
*> foo-factory can be treated like a normal object reference.
INVOKE foo-factory "someMethod"</syntaxhighlight>
Line 224 ⟶ 259:
=={{header|CoffeeScript}}==
While CoffeeScript does provide a useful class abstraction around its prototype-based inheritance, there aren't any actual classes.
<syntaxhighlight lang="coffeescript">class Foo
@staticMethod: -> 'Bar'
 
Line 233 ⟶ 268:
foo.instanceMethod() #=> 'Baz'
Foo.staticMethod() #=> 'Bar'</syntaxhighlight>
 
 
=={{header|Common Lisp}}==
In Common Lisp, classmethods are methods that apply to classes, rather than classes that contain methods.
<syntaxhighlight lang="lisp">(defclass my-class ()
((x
:accessor get-x ;; getter function
Line 259 ⟶ 295:
Value of x^2: 100
</pre>
 
 
=={{header|D}}==
<syntaxhighlight lang="d">struct Cat {
static int staticMethod() {
return 2;
Line 298 ⟶ 335:
assert(d.dynamicMethod() == "Woof!");
}</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}}==
Making an object of class and then calling it.
<syntaxhighlight lang=Dragon"dragon">r = new run()
r.val()</syntaxhighlight>
 
=={{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.
 
<syntaxhighlight lang="dyalect">//Static method on a built-in type Integer
static func Integer.Div(x, y) {
x / y
Line 325 ⟶ 449:
<pre>4
4</pre>
 
=={{header|E}}==
{{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.
 
<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.
 
=={{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}}==
The message call:
<syntaxhighlight lang="elena">
console.printLine("Hello"," ","World!");
</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="elixir">
defmodule ObjectCall do
def new() do
Line 371 ⟶ 552:
IO.puts(obj |> ObjectCall.concat("Hello ", "World!"))
</syntaxhighlight>
 
=={{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}}==
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.
 
<syntaxhighlight lang="factor">USING: accessors io kernel literals math sequences ;
IN: rosetta-code.call-a-method
 
Line 407 ⟶ 607:
I don't know how to speak!
</pre>
 
=={{header|Forth}}==
{{works with|4tH|3.62.0}}
{{trans|D}}
There are numerous, mutually incompatible object oriented frameworks for Forth. This one works with the FOOS preprocessor extension of [[4tH]].
<syntaxhighlight lang="forth">include lib/compare.4th
include 4pp/lib/foos.4pp
 
Line 457 ⟶ 656:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<syntaxhighlight lang="forth">include FMS-SI.f
 
:class animal
Line 487 ⟶ 686:
Sparky speak \ => woof ok
</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang=Fortran"fortran">
! type declaration
type my_type
Line 507 ⟶ 705:
 
</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
' FB 1.05.0 Win64
 
Line 540 ⟶ 737:
Hello 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>
 
=={{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.
<syntaxhighlight lang="go">type Foo int // some custom type
 
// method on the type itself; can be called on that type or its pointer
Line 576 ⟶ 804:
 
An example package:
<syntaxhighlight lang="go">package box
 
import "sync/atomic"
Line 606 ⟶ 834:
}</syntaxhighlight>
Example use:
<syntaxhighlight lang="go">package main
 
import "box"
Line 627 ⟶ 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.
<syntaxhighlight lang="unicon">procedure main()
 
bar := foo() # create instance
Line 650 ⟶ 878:
L := [cp1]
end</syntaxhighlight>
 
=={{header|Haskell}}==
 
Line 660 ⟶ 887:
 
Dummy example:
<syntaxhighlight lang="haskell">data Obj = Obj { field :: Int, method :: Int -> Int }
 
-- smart constructor
Line 685 ⟶ 912:
*Main> show o2
Obj 5</pre>
 
=={{header|J}}==
 
Line 694 ⟶ 920:
Static:
 
<syntaxhighlight lang="j">methodName_className_ parameters</syntaxhighlight>
 
and, given an object instance reference:
 
<syntaxhighlight lang="j">objectReference=:'' conew 'className'</syntaxhighlight>
 
an instance invocation could be:
 
<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.
 
<syntaxhighlight lang="j">parameters methodName_className_ parameters</syntaxhighlight>
or
<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.
Line 714 ⟶ 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:
 
<syntaxhighlight lang="j">classReference=: <'className'
methodName__classReference parameters</syntaxhighlight>
 
Line 721 ⟶ 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
 
<syntaxhighlight lang="j">methodName_123_ parameters</syntaxhighlight>
 
This last case can be useful when debugging.
 
=={{header|Java}}==
Static methods in Java are usually called by using the dot operator on a class name:
<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:
<syntaxhighlight lang="java">ClassWithMethod varName = new ClassWithMethod();
varName.methodName(argument1, argument2);
//or
Line 739 ⟶ 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.
 
=={{header|JavaScript}}==
If you have a object called <tt>x</tt> and a method called <tt>y</tt> then you can write:
<syntaxhighlight lang="javascript">x.y()</syntaxhighlight>
 
=={{header|Julia}}==
module Animal
Line 774 ⟶ 997:
#
masskg(x) = x.weight
 
=={{header|Kotlin}}==
Kotlin does not have static methods as such, but they can be easily simulated by '<code>companion object'</code> methods :.
 
<syntaxhighlight lang=scala>class MyClass {
<syntaxhighlight lang="kotlin">class MyClass {
fun instanceMethod(s: String) = println(s)
 
Line 785 ⟶ 1,008:
}
 
fun main(args: Array<String>) {
val mc = MyClass()
mc.instanceMethod("Hello instance world!")
Line 800 ⟶ 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.
<syntaxhighlight lang="latitude">myObject someMethod (arg1, arg2, arg3).
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.
<syntaxhighlight lang="latitude">myObject someMethod "string constant argument".
myObject someMethod (argument). ;; Parentheses are necessary here
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.
<syntaxhighlight lang="latitude">myObject someMethod: arg1, arg2, arg3.</syntaxhighlight>
 
=={{header|LFE}}==
 
Line 819 ⟶ 1,041:
 
===With Closures===
<syntaxhighlight lang="lisp">(defmodule aquarium
(export all))
 
Line 915 ⟶ 1,137:
 
With this done, one can create objects and interact with them. Here is some usage from the LFE REPL:
<syntaxhighlight lang="lisp">; Load the file and create a fish-class instance:
 
> (slurp '"object.lfe")
Line 962 ⟶ 1,184:
 
===With Lightweight Processes===
<syntaxhighlight lang="lisp">(defmodule object
(export all))
 
Line 1,065 ⟶ 1,287:
 
Here is some usage from the LFE REPL:
<syntaxhighlight lang="lisp">; Load the file and create a fish-class instance:
 
> (slurp '"object.lfe")
Line 1,110 ⟶ 1,332:
"3e64e5c20fb742dd88dac1032749c2fd"]
ok</syntaxhighlight>
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">-- call static method
script("MyClass").foo()
 
Line 1,118 ⟶ 1,339:
obj = script("MyClass").new()
obj.foo()</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="logtalk">
% avoid infinite metaclass regression by
% making the metaclass an instance of itself
Line 1,133 ⟶ 1,353:
:- end_object.
</syntaxhighlight>
<syntaxhighlight lang="logtalk">
:- object(class,
instantiates(metaclass)).
Line 1,144 ⟶ 1,364:
:- end_object.
</syntaxhighlight>
<syntaxhighlight lang="logtalk">
:- object(instance,
instantiates(class)).
Line 1,151 ⟶ 1,371:
</syntaxhighlight>
Testing:
<syntaxhighlight lang="logtalk">
| ?- class::me(Me).
Me = class
Line 1,160 ⟶ 1,380:
yes
</syntaxhighlight>
 
=={{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.
 
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:
<syntaxhighlight lang="lua">local object = { name = "foo", func = function (self) print(self.name) end }
 
object:func() -- with : sugar
Line 1,171 ⟶ 1,390:
 
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:
<syntaxhighlight lang="lua">local methods = { }
function methods:func () -- if a function is declared using :, it is given an implicit 'self' parameter
print(self.name)
Line 1,184 ⟶ 1,403:
 
Example module, named <code>box.lua</code>:
<syntaxhighlight lang="lua">local count = 0
local box = { }
local boxmt = { __index = box }
Line 1,202 ⟶ 1,421:
 
Example use:
<syntaxhighlight lang="lua">local box = require 'box'
 
local b = box.new()
Line 1,208 ⟶ 1,427:
print(b:tellSecret())
print(box.count())</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
In M2000 there are some kinds of objects. Group is the one typean 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"m2000 Interpreterinterpreter">
Module CheckIt {
\\ A class definition is a function which return a Group
Line 1,264 ⟶ 1,482:
=={{header|Maple}}==
There is no real difference in how you call a static or instance method.
<syntaxhighlight lang=Maple"maple"># Static
Method( obj, other, arg );</syntaxhighlight>
<syntaxhighlight lang=Maple"maple"># Instance
Method( obj, other, arg );</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang=MiniScript"miniscript">Dog = {}
Dog.name = ""
Dog.help = function()
Line 1,289 ⟶ 1,506:
<pre>This class represents dogs.
Fido says Woof!</pre>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang=Nanoquery"nanoquery">class MyClass
declare static id = 5
declare MyName
Line 1,321 ⟶ 1,537:
<pre>5
test</pre>
 
=={{header|Nemerle}}==
<syntaxhighlight lang=Nemerle"nemerle">// Static
MyClass.Method(someParameter);
// Instance
myInstance.Method(someParameter);</syntaxhighlight>
 
=={{header|NetRexx}}==
Like [[#Java|Java]], static methods in NetRexx are called by using the dot operator on a class name:
<syntaxhighlight lang=NetRexx"netrexx">SomeClass.staticMethod()</syntaxhighlight>
Instance methods are called by using the dot operator on an instance:
<syntaxhighlight lang=NetRexx"netrexx">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</syntaxhighlight>
 
=={{header|Nim}}==
In Nim there are no object methods, but regular procedures can be called with method call syntax:
<syntaxhighlight lang="nim">var x = @[1, 2, 3]
add(x, 4)
x.add(5)</syntaxhighlight>
 
=={{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 following code calls a method called <tt>&amp;GO</tt> on the current object:
<syntaxhighlight lang="oasys_oaa">+&GO</syntaxhighlight>
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
ClassName->some_function(); # call class function
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.
 
=={{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.
 
<syntaxhighlight lang="pascal">// Static (known in Pascal as class method)
MyClass.method(someParameter);
 
Line 1,366 ⟶ 1,576:
myInstance.method(someParameter);
</syntaxhighlight>
 
=={{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).
<syntaxhighlight lang="objc">// Class
[MyClass method:someParameter];
// or equivalently:
Line 1,383 ⟶ 1,592:
// Method with no arguments
[myInstance method];</syntaxhighlight>
 
=={{header|OCaml}}==
 
We can only call the method of an instantiated object:
 
<syntaxhighlight lang="ocaml">my_obj#my_meth params</syntaxhighlight>
 
=={{header|Oforth}}==
When a method is called, the top of the stack is used as the object on which the method will be applyed :
<syntaxhighlight lang=Oforth"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) :
<syntaxhighlight lang=Oforth"oforth">Date now</syntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang=ooRexx"oorexx">say "pi:" .circle~pi
c=.circle~new(1)
say "c~area:" c~area
Line 1,434 ⟶ 1,640:
c~area: 3.14159265
10 circles were created</pre>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl"># Class method
MyClass->classMethod($someParameter);
# Equivalently using a class name
Line 1,453 ⟶ 1,658:
MyClass::classMethod('MyClass', $someParameter);
MyClass::method($myInstance, $someParameter);</syntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/Class}}
Line 1,459 ⟶ 1,663:
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.
<!--<syntaxhighlight lang=Phix"phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no class in p2js)</span>
<span style="color: #008080;">class</span> <span style="color: #000000;">test</span>
Line 1,472 ⟶ 1,676:
<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}}==
<syntaxhighlight lang="php">// Static method
MyClass::method($someParameter);
// In PHP 5.3+, static method can be called on a string of the class name
Line 1,483 ⟶ 1,686:
// Instance method
$myInstance->method($someParameter);</syntaxhighlight>
 
=={{header|PicoLisp}}==
Method invocation is syntactically equivalent to normal function calls. Method names have a trailing '>' by convention.
<syntaxhighlight lang=PicoLisp"picolisp">(foo> MyClass)
(foo> MyObject)</syntaxhighlight>
 
=={{header|Pike}}==
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:
<syntaxhighlight lang=Pike"pike">obj->method();
obj["method"]();
call_function(obj->method);
Line 1,500 ⟶ 1,701:
 
because <code>()</code> is actually an operator that is applied to a function reference, the following is also possible:
<syntaxhighlight lang=Pike"pike">function func = obj->method;
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:
<syntaxhighlight lang=Pike"pike">module.func();
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.
 
=={{header|PL/SQL}}==
<syntaxhighlight lang=PLSQL"plsql">create or replace TYPE myClass AS OBJECT (
-- A class needs at least one member even though we don't use it
dummy NUMBER,
Line 1,535 ⟶ 1,735:
DBMS_OUTPUT.put_line( myInstance.instance_method() );
END;/</syntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell"powershell">$Date = Get-Date
$Date.AddDays( 1 )
[System.Math]::Sqrt( 2 )</syntaxhighlight>
 
=={{header|Processing}}==
<syntaxhighlight lang="processing">// define a rudimentary class
class HelloWorld
{
Line 1,563 ⟶ 1,761:
// and call the instance method
hello.sayGoodbye();</syntaxhighlight>
 
=={{header|Python}}==
<syntaxhighlight lang="python">class MyClass(object):
@classmethod
def myClassMethod(self, x):
Line 1,589 ⟶ 1,786:
myInstance.myClassMethod(someParameter)
myInstance.myStaticMethod(someParameter)</syntaxhighlight>
 
=={{header|Quackery}}==
 
Line 1,599 ⟶ 1,795:
(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"quackery">( ---------------- zen object orientation -------------- )
[ immovable
Line 1,696 ⟶ 1,892:
Resetting mycounter.
Current value of mycounter: 0</pre>
 
=={{header|Racket}}==
 
The following snippet shows a call to the <tt>start</tt> method of the <tt>timer%</tt> class.
 
<syntaxhighlight lang="racket">#lang racket/gui
 
(define timer (new timer%))
(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' }
 
Line 1,742 ⟶ 1,936:
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;
Line 1,753 ⟶ 1,947:
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 {
Line 1,761 ⟶ 1,955:
say $object.&example-method; # Outputs "This is a string."
</syntaxhighlight>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
new point { print() }
Class Point
Line 1,769 ⟶ 1,962:
func print see x + nl + y + nl + z + nl
</syntaxhighlight>
<syntaxhighlight lang="ring">
o1 = new System.output.console
o1.print("Hello World")
Line 1,778 ⟶ 1,971:
see cText + nl
</syntaxhighlight>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby"># Class method
MyClass.some_method(some_parameter)
 
Line 1,796 ⟶ 1,988:
# Calling a method with no parameters
my_instance.another_method</syntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">struct Foo;
 
impl Foo {
Line 1,829 ⟶ 2,020:
println!("The answer to life is still {}." lots_of_references.get_the_answer_to_life());
}</syntaxhighlight>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">/* This class implicitly includes a constructor which accepts an Int and
* creates "val variable1: Int" with that value.
*/
Line 1,855 ⟶ 2,045:
println("Successfully completed without error.")
}</syntaxhighlight>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">class MyClass {
method foo(arg) { say arg }
}
Line 1,880 ⟶ 2,069:
# Alternatively, by asking for a method
instance.method(:foo)(arg);</syntaxhighlight>
 
=={{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.
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)
 
<syntaxhighlight lang="smalltalk">" Class "
MyClass selector: someArgument .
" or equivalently "
Line 1,905 ⟶ 2,093:
 
Example for dynamic class determination:
<syntaxhighlight lang="smalltalk">theCar := (someCondition ifTrue:[ Ford ] ifFalse: [ Jaguar ]) new.</syntaxhighlight>
 
Message names (selectors) can be chosen or constructed dynamically at runtime. For example:
<syntaxhighlight lang="smalltalk">whichMessage := #( #'red' #'green' #'blue') at: computedIndex.
foo perform: whichMessage</syntaxhighlight>
 
or:
 
<syntaxhighlight lang="smalltalk">theMessage := ('handleFileType' , suffix) asSymbol.
foo perform: theMessage.</syntaxhighlight>
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).
<syntaxhighlight lang="smalltalk">[
foo perform: theMessage
] on: MessageNotUnderstood do:[
Dialog information: 'sorry'
]</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang=SuperCollider"supercollider">
SomeClass {
Line 1,944 ⟶ 2,131:
a.someInstanceMethod;
</syntaxhighlight>
 
=={{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).
<syntaxhighlight lang="swift">// Class
MyClass.method(someParameter)
// or equivalently:
Line 1,958 ⟶ 2,144:
// Method with multiple arguments
myInstance.method(red:arg1, green:arg2, blue:arg3)</syntaxhighlight>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">package require Tcl 8.6
# "Static" (on class object)
MyClass mthd someParameter
Line 1,966 ⟶ 2,151:
# Instance
$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}}==
<syntaxhighlight lang="ursa"># create an instance of the built-in file class
decl file f
 
Line 1,976 ⟶ 2,202:
=={{header|VBA}}==
First we have to create a class module named "myObject" :
<syntaxhighlight lang="vb">
Option Explicit
 
Line 1,991 ⟶ 2,217:
End Sub</syntaxhighlight>
In a "standard" Module, the call should be :
<syntaxhighlight lang="vb">Option Explicit
 
Sub test()
Line 2,005 ⟶ 2,231:
 
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=ecmascript"wren>class MyClass {
construct new() {}
method() { System.print("instance method called") }
Line 2,027 ⟶ 2,317:
You can call object methods using two types of structures. Classes and Objects.
===Classes===
<syntaxhighlight lang=XBS"xbs">class MyClass {
construct=func(self,Props){
self:Props=Props;
Line 2,043 ⟶ 2,333:
</pre>
===Objects===
<syntaxhighlight lang=XBS"xbs">set MyObj = {
a=10;
AddA=func(self,x){
Line 2,055 ⟶ 2,345:
12
</pre>
 
=={{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.
<syntaxhighlight lang="xlisp">(DEFINE-CLASS MY-CLASS)
 
(DEFINE-CLASS-METHOD (MY-CLASS 'DO-SOMETHING-WITH SOME-PARAMETER)
Line 2,086 ⟶ 2,375:
I am an instance of the class -- #<Object:MY-CLASS #x39979d0>
You sent me the parameter BAR</pre>
 
=={{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.
 
<syntaxhighlight lang="zig">const asserttesting = @import("std").debug.asserttesting;
 
pub const ID = struct {
Line 2,120 ⟶ 2,408:
};
 
assert(person1.// test getAge() ==method 18);call
asserttry testing.expectEqual(ID@as(u7, 18), person1.getAge(person2) == 20);
try testing.expectEqual(@as(u7, 20), ID.getAge(person2));
}</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="zkl">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
Line 2,141 ⟶ 2,430:
{{omit from|360 Assembly}}
{{omit from|6502 Assembly}}
{{omit from|68000 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}}
Line 2,160 ⟶ 2,449:
{{omit from|Octave}}
{{omit from|PARI/GP}}
{{omit from|Plain English|Plain English does not support objects.}}
{{omit from|Retro}}
{{omit from|REXX|not OO}}
9,485

edits