Call an object method: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (sntax highlighting fixup automation) |
|||
Line 8: | Line 8: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang=actionscript>// Static |
||
MyClass.method(someParameter); |
MyClass.method(someParameter); |
||
// Instance |
// Instance |
||
myInstance.method(someParameter);</ |
myInstance.method(someParameter);</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
Line 22: | Line 22: | ||
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: |
||
< |
<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 29: | ||
private |
private |
||
type Object is tagged null record; |
type Object is tagged null record; |
||
end My_Class;</ |
end My_Class;</syntaxhighlight> |
||
Implement the package: |
Implement the package: |
||
< |
<syntaxhighlight lang=Ada> package body My_Class is |
||
procedure Primitive(Self: Object) is |
procedure Primitive(Self: Object) is |
||
begin |
begin |
||
Line 49: | Line 49: | ||
Put_Line("Greetings"); |
Put_Line("Greetings"); |
||
end Static; |
end Static; |
||
end My_Class;</ |
end My_Class;</syntaxhighlight> |
||
Specify and implement a subclass of My_Class: |
Specify and implement a subclass of My_Class: |
||
< |
<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 62: | ||
Put_Line("Hello Universe!"); |
Put_Line("Hello Universe!"); |
||
end Primitive; |
end Primitive; |
||
end Other_Class;</ |
end Other_Class;</syntaxhighlight> |
||
The main program, making the dynamic and static calls: |
The main program, making the dynamic and static calls: |
||
< |
<syntaxhighlight lang=Ada>with Ada.Text_IO; use Ada.Text_IO; |
||
procedure Call_Method is |
procedure Call_Method is |
||
Line 85: | Line 85: | ||
Ob1.Dynamic; |
Ob1.Dynamic; |
||
Ob2.Dynamic; |
Ob2.Dynamic; |
||
end Call_Method;</ |
end Call_Method;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 96: | Line 96: | ||
=={{header|Apex}}== |
=={{header|Apex}}== |
||
< |
<syntaxhighlight lang=Java>// Static |
||
MyClass.method(someParameter); |
MyClass.method(someParameter); |
||
// Instance |
// Instance |
||
myInstance.method(someParameter);</ |
myInstance.method(someParameter);</syntaxhighlight> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
{{works with|AutoHotkey_L}} |
{{works with|AutoHotkey_L}} |
||
(AutoHotkey Basic does not have classes) |
(AutoHotkey Basic does not have classes) |
||
< |
<syntaxhighlight lang=AHK>class myClass |
||
{ |
{ |
||
Method(someParameter){ |
Method(someParameter){ |
||
Line 114: | Line 114: | ||
myClass.method("hi") |
myClass.method("hi") |
||
myInstance := new myClass |
myInstance := new myClass |
||
myInstance.Method("bye")</ |
myInstance.Method("bye")</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
Line 120: | Line 120: | ||
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. |
||
< |
<syntaxhighlight lang=bracmat>( ( myClass |
||
= (name=aClass) |
= (name=aClass) |
||
( Method |
( Method |
||
Line 132: | Line 132: | ||
& !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" |
||
);</ |
);</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Output from aClass: Example of calling a 'class' method |
<pre>Output from aClass: Example of calling a 'class' method |
||
Line 140: | Line 140: | ||
=={{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 168: | Line 168: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
And yes, it works : |
And yes, it works : |
||
<pre> |
<pre> |
||
Line 177: | Line 177: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang=cpp>// Static |
||
MyClass::method(someParameter); |
MyClass::method(someParameter); |
||
Line 185: | Line 185: | ||
// Pointer |
// Pointer |
||
MyPointer->method(someParameter); |
MyPointer->method(someParameter); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C_sharp|C#}}== |
=={{header|C_sharp|C#}}== |
||
< |
<syntaxhighlight lang=csharp>// Static |
||
MyClass.Method(someParameter); |
MyClass.Method(someParameter); |
||
// Instance |
// Instance |
||
myInstance.Method(someParameter);</ |
myInstance.Method(someParameter);</syntaxhighlight> |
||
=={{header|ChucK}}== |
=={{header|ChucK}}== |
||
<syntaxhighlight lang=c> |
|||
<lang c> |
|||
MyClass myClassObject; |
MyClass myClassObject; |
||
myClassObject.myFunction(some parameter); |
myClassObject.myFunction(some parameter); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<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</ |
(. 1 (equals 2)) ; alternative style</syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
COBOL has two ways to invoke a method: the <code>INVOKE</code> statement and inline method invocation. |
COBOL has two ways to invoke a method: the <code>INVOKE</code> statement and inline method invocation. |
||
< |
<syntaxhighlight lang=cobol>*> INVOKE |
||
INVOKE FooClass "someMethod" RETURNING bar *> Factory object |
INVOKE FooClass "someMethod" RETURNING bar *> Factory object |
||
INVOKE foo-instance "anotherMethod" RETURNING bar *> Instance object |
INVOKE foo-instance "anotherMethod" RETURNING bar *> Instance object |
||
Line 215: | Line 215: | ||
*> Inline method invocation |
*> Inline method invocation |
||
MOVE FooClass::"someMethod" TO bar *> Factory object |
MOVE FooClass::"someMethod" TO bar *> Factory object |
||
MOVE foo-instance::"anotherMethod" TO bar *> Instance object</ |
MOVE foo-instance::"anotherMethod" TO bar *> 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. |
||
< |
<syntaxhighlight lang=cobol>INVOKE foo-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"</ |
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. |
||
< |
<syntaxhighlight lang=coffeescript>class Foo |
||
@staticMethod: -> 'Bar' |
@staticMethod: -> 'Bar' |
||
Line 232: | Line 232: | ||
foo.instanceMethod() #=> 'Baz' |
foo.instanceMethod() #=> 'Baz' |
||
Foo.staticMethod() #=> 'Bar'</ |
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. |
||
< |
<syntaxhighlight lang=lisp>(defclass my-class () |
||
((x |
((x |
||
:accessor get-x ;; getter function |
:accessor get-x ;; getter function |
||
Line 253: | Line 253: | ||
(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 261: | Line 261: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang=d>struct Cat { |
||
static int staticMethod() { |
static int staticMethod() { |
||
return 2; |
return 2; |
||
Line 297: | Line 297: | ||
d = new Dog; |
d = new Dog; |
||
assert(d.dynamicMethod() == "Woof!"); |
assert(d.dynamicMethod() == "Woof!"); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Dragon}}== |
=={{header|Dragon}}== |
||
Making an object of class and then calling it. |
Making an object of class and then calling it. |
||
< |
<syntaxhighlight lang=Dragon>r = new run() |
||
r.val()</ |
r.val()</syntaxhighlight> |
||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
Line 308: | Line 308: | ||
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. |
||
< |
<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 |
||
Line 319: | Line 319: | ||
print(Integer.Div(12, 3)) |
print(Integer.Div(12, 3)) |
||
print(12.Div(3))</ |
print(12.Div(3))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 330: | Line 330: | ||
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 |
<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. |
||
Line 336: | Line 336: | ||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
The message call: |
The message call: |
||
< |
<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. |
||
< |
<syntaxhighlight lang=elixir> |
||
defmodule ObjectCall do |
defmodule ObjectCall do |
||
def new() do |
def new() do |
||
Line 370: | Line 370: | ||
IO.puts(obj |> ObjectCall.concat("Hello ", "World!")) |
IO.puts(obj |> ObjectCall.concat("Hello ", "World!")) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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. |
||
< |
<syntaxhighlight lang=factor>USING: accessors io kernel literals math sequences ; |
||
IN: rosetta-code.call-a-method |
IN: rosetta-code.call-a-method |
||
Line 399: | Line 399: | ||
0.75 <cat> speak |
0.75 <cat> speak |
||
0.1 <cat> speak |
0.1 <cat> speak |
||
"bird" speak</ |
"bird" speak</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 412: | Line 412: | ||
{{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]]. |
||
< |
<syntaxhighlight lang=forth>include lib/compare.4th |
||
include 4pp/lib/foos.4pp |
include 4pp/lib/foos.4pp |
||
Line 451: | Line 451: | ||
; \ same for dynamic methods |
; \ same for dynamic methods |
||
main</ |
main</syntaxhighlight> |
||
Works with any ANS Forth |
Works with any ANS Forth |
||
Line 457: | Line 457: | ||
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 |
||
< |
<syntaxhighlight lang=forth>include FMS-SI.f |
||
:class animal |
:class animal |
||
Line 486: | Line 486: | ||
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> |
||
! type declaration |
! type declaration |
||
type my_type |
type my_type |
||
Line 506: | Line 506: | ||
mytype_object%method2() ! call method2 defined as function |
mytype_object%method2() ! call method2 defined as function |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang=freebasic> |
||
' FB 1.05.0 Win64 |
' FB 1.05.0 Win64 |
||
Line 534: | Line 534: | ||
Print "Press any key to quit the program" |
Print "Press any key to quit the program" |
||
Sleep |
Sleep |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 544: | Line 544: | ||
=={{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. |
||
< |
<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 572: | Line 572: | ||
Foo.ValueMethod(myValue, someParameter) |
Foo.ValueMethod(myValue, someParameter) |
||
(*Foo).PointerMethod(myPointer, someParameter) |
(*Foo).PointerMethod(myPointer, someParameter) |
||
(*Foo).ValueMethod(myPointer, someParameter)</ |
(*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: |
||
< |
<syntaxhighlight lang=go>package box |
||
import "sync/atomic" |
import "sync/atomic" |
||
Line 604: | Line 604: | ||
func Count() uint32 { |
func Count() uint32 { |
||
return atomic.LoadUint32(&sn) |
return atomic.LoadUint32(&sn) |
||
}</ |
}</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang=go>package main |
||
import "box" |
import "box" |
||
Line 621: | Line 621: | ||
// Call class method. In Go terms, another exported function. |
// Call class method. In Go terms, another exported function. |
||
box.Count() |
box.Count() |
||
}</ |
}</syntaxhighlight> |
||
==Icon and {{header|Unicon}}== |
==Icon and {{header|Unicon}}== |
||
Line 627: | Line 627: | ||
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. |
||
< |
<syntaxhighlight lang=unicon>procedure main() |
||
bar := foo() # create instance |
bar := foo() # create instance |
||
Line 649: | Line 649: | ||
initially |
initially |
||
L := [cp1] |
L := [cp1] |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Line 660: | Line 660: | ||
Dummy example: |
Dummy example: |
||
< |
<syntaxhighlight lang=haskell>data Obj = Obj { field :: Int, method :: Int -> Int } |
||
-- smart constructor |
-- smart constructor |
||
Line 668: | Line 668: | ||
-- adding method from a type class |
-- adding method from a type class |
||
instanse Show Obj where |
instanse Show Obj where |
||
show o = "Obj " ++ show (field o) </ |
show o = "Obj " ++ show (field o) </syntaxhighlight> |
||
<pre>*Main> let o1 = Obj 1 (*5) |
<pre>*Main> let o1 = Obj 1 (*5) |
||
Line 694: | Line 694: | ||
Static: |
Static: |
||
<lang |
<syntaxhighlight lang=j>methodName_className_ parameters</syntaxhighlight> |
||
and, given an object instance reference: |
and, given an object instance reference: |
||
< |
<syntaxhighlight lang=j>objectReference=:'' conew 'className'</syntaxhighlight> |
||
an instance invocation could be: |
an instance invocation could be: |
||
<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 |
<syntaxhighlight lang=j>parameters methodName_className_ parameters</syntaxhighlight> |
||
or |
or |
||
<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 714: | Line 714: | ||
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: |
||
< |
<syntaxhighlight lang=j>classReference=: <'className' |
||
methodName__classReference parameters</ |
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 721: | Line 721: | ||
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 |
<syntaxhighlight lang=j>methodName_123_ parameters</syntaxhighlight> |
||
This last case can be useful when debugging. |
This last case can be useful when debugging. |
||
Line 727: | Line 727: | ||
=={{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: |
||
< |
<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: |
||
< |
<syntaxhighlight lang=java>ClassWithMethod varName = new ClassWithMethod(); |
||
varName.methodName(argument1, argument2); |
varName.methodName(argument1, argument2); |
||
//or |
//or |
||
new ClassWithMethod().methodName(argument1, argument2);</ |
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 742: | Line 742: | ||
=={{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 |
<syntaxhighlight lang=javascript>x.y()</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Line 777: | Line 777: | ||
=={{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 as such but they can be easily simulated by 'companion object' methods : |
||
< |
<syntaxhighlight lang=scala>class MyClass { |
||
fun instanceMethod(s: String) = println(s) |
fun instanceMethod(s: String) = println(s) |
||
Line 789: | Line 789: | ||
mc.instanceMethod("Hello instance world!") |
mc.instanceMethod("Hello instance world!") |
||
MyClass.staticMethod("Hello static world!") |
MyClass.staticMethod("Hello static world!") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 800: | Line 800: | ||
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. |
||
< |
<syntaxhighlight lang=latitude>myObject someMethod (arg1, arg2, arg3). |
||
MyClass 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. |
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 (argument). ;; Parentheses are necessary here |
||
myObject someMethod. ;; No arguments</ |
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. |
||
< |
<syntaxhighlight lang=latitude>myObject someMethod: arg1, arg2, arg3.</syntaxhighlight> |
||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
Line 819: | Line 819: | ||
===With Closures=== |
===With Closures=== |
||
< |
<syntaxhighlight lang=lisp>(defmodule aquarium |
||
(export all)) |
(export all)) |
||
Line 912: | Line 912: | ||
(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: |
||
< |
<syntaxhighlight lang=lisp>; Load the file and create a fish-class instance: |
||
> (slurp '"object.lfe") |
> (slurp '"object.lfe") |
||
Line 959: | Line 959: | ||
children: ["fdcf35983bb496650e558a82e34c9935", |
children: ["fdcf35983bb496650e558a82e34c9935", |
||
"3e64e5c20fb742dd88dac1032749c2fd"] |
"3e64e5c20fb742dd88dac1032749c2fd"] |
||
ok</ |
ok</syntaxhighlight> |
||
===With Lightweight Processes=== |
===With Lightweight Processes=== |
||
< |
<syntaxhighlight lang=lisp>(defmodule object |
||
(export all)) |
(export all)) |
||
Line 1,062: | Line 1,062: | ||
(defun get-children-count (object) |
(defun get-children-count (object) |
||
(call-method object 'children-count))</ |
(call-method object 'children-count))</syntaxhighlight> |
||
Here is some usage from the LFE REPL: |
Here is some usage from the LFE REPL: |
||
< |
<syntaxhighlight lang=lisp>; Load the file and create a fish-class instance: |
||
> (slurp '"object.lfe") |
> (slurp '"object.lfe") |
||
Line 1,109: | Line 1,109: | ||
children: ["fdcf35983bb496650e558a82e34c9935", |
children: ["fdcf35983bb496650e558a82e34c9935", |
||
"3e64e5c20fb742dd88dac1032749c2fd"] |
"3e64e5c20fb742dd88dac1032749c2fd"] |
||
ok</ |
ok</syntaxhighlight> |
||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<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()</ |
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. |
||
< |
<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,132: | Line 1,132: | ||
:- end_object. |
:- end_object. |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang=logtalk> |
||
:- object(class, |
:- object(class, |
||
instantiates(metaclass)). |
instantiates(metaclass)). |
||
Line 1,143: | Line 1,143: | ||
:- end_object. |
:- end_object. |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang=logtalk> |
||
:- object(instance, |
:- object(instance, |
||
instantiates(class)). |
instantiates(class)). |
||
:- end_object. |
:- end_object. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Testing: |
Testing: |
||
< |
<syntaxhighlight lang=logtalk> |
||
| ?- class::me(Me). |
| ?- class::me(Me). |
||
Me = class |
Me = class |
||
Line 1,159: | Line 1,159: | ||
Class = class |
Class = class |
||
yes |
yes |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Line 1,165: | Line 1,165: | ||
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: |
||
< |
<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</ |
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: |
||
< |
<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,179: | Line 1,179: | ||
object:func() -- with : sugar |
object:func() -- with : sugar |
||
methods.func(object) -- without : sugar</ |
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>: |
||
< |
<syntaxhighlight lang=lua>local count = 0 |
||
local box = { } |
local box = { } |
||
local boxmt = { __index = box } |
local boxmt = { __index = box } |
||
Line 1,199: | Line 1,199: | ||
return count |
return count |
||
end |
end |
||
return M</ |
return M</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang=lua>local box = require 'box' |
||
local b = box.new() |
local b = box.new() |
||
print(b:tellSecret()) |
print(b:tellSecret()) |
||
print(box.count())</ |
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 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 |
||
< |
<syntaxhighlight 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,260: | Line 1,260: | ||
} |
} |
||
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. |
||
< |
<syntaxhighlight lang=Maple># Static |
||
Method( obj, other, arg );</ |
Method( obj, other, arg );</syntaxhighlight> |
||
< |
<syntaxhighlight lang=Maple># Instance |
||
Method( obj, other, arg );</ |
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. |
||
< |
<syntaxhighlight lang=MiniScript>Dog = {} |
||
Dog.name = "" |
Dog.name = "" |
||
Dog.help = function() |
Dog.help = function() |
||
Line 1,284: | Line 1,284: | ||
Dog.help // calling a "class method" |
Dog.help // calling a "class method" |
||
fido.speak // calling an "instance method"</ |
fido.speak // calling an "instance method"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,291: | Line 1,291: | ||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
< |
<syntaxhighlight lang=Nanoquery>class MyClass |
||
declare static id = 5 |
declare static id = 5 |
||
declare MyName |
declare MyName |
||
Line 1,317: | Line 1,317: | ||
// and call the class method |
// and call the class method |
||
myclass = new(MyClass, "test") |
myclass = new(MyClass, "test") |
||
println myclass.getName()</ |
println myclass.getName()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>5 |
<pre>5 |
||
Line 1,323: | Line 1,323: | ||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang=Nemerle>// Static |
||
MyClass.Method(someParameter); |
MyClass.Method(someParameter); |
||
// Instance |
// Instance |
||
myInstance.Method(someParameter);</ |
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 |
<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: |
||
< |
<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</ |
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: |
||
< |
<syntaxhighlight lang=nim>var x = @[1, 2, 3] |
||
add(x, 4) |
add(x, 4) |
||
x.add(5)</ |
x.add(5)</syntaxhighlight> |
||
=={{header|OASYS Assembler}}== |
=={{header|OASYS Assembler}}== |
||
Line 1,348: | Line 1,348: | ||
The following code calls a method called <tt>&GO</tt> on the current object: |
The following code calls a method called <tt>&GO</tt> on the current object: |
||
<lang |
<syntaxhighlight lang=oasys_oaa>+&GO</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang=objeck> |
||
ClassName->some_function(); # call class function |
ClassName->some_function(); # call class function |
||
instance->some_method(); # call instance method</ |
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. |
||
Line 1,360: | Line 1,360: | ||
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. |
||
< |
<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). |
||
< |
<syntaxhighlight lang=objc>// Class |
||
[MyClass method:someParameter]; |
[MyClass method:someParameter]; |
||
// or equivalently: |
// or equivalently: |
||
Line 1,382: | Line 1,382: | ||
// Method with no arguments |
// Method with no arguments |
||
[myInstance method];</ |
[myInstance method];</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Line 1,388: | Line 1,388: | ||
We can only call the method of an instantiated object: |
We can only call the method of an instantiated object: |
||
<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 |
<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 |
<syntaxhighlight lang=Oforth>Date now</syntaxhighlight> |
||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
< |
<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,427: | Line 1,427: | ||
Say self~class |
Say self~class |
||
Say self |
Say self |
||
return self~class~pi * radius * radius </ |
return self~class~pi * radius * radius </syntaxhighlight> |
||
'''Output:''' |
'''Output:''' |
||
<pre>pi: 3.14159265358979323 |
<pre>pi: 3.14159265358979323 |
||
Line 1,436: | Line 1,436: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang=perl># Class method |
||
MyClass->classMethod($someParameter); |
MyClass->classMethod($someParameter); |
||
# Equivalently using a class name |
# Equivalently using a class name |
||
Line 1,452: | Line 1,452: | ||
# 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);</ |
MyClass::method($myInstance, $someParameter);</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Line 1,459: | Line 1,459: | ||
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)--> |
||
<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;">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> |
<span style="color: #008080;">class</span> <span style="color: #000000;">test</span> |
||
Line 1,471: | Line 1,471: | ||
<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> |
<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> |
||
<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> |
<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}}== |
||
< |
<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,482: | Line 1,482: | ||
// Instance method |
// Instance method |
||
$myInstance->method($someParameter);</ |
$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. |
||
< |
<syntaxhighlight lang=PicoLisp>(foo> MyClass) |
||
(foo> MyObject)</ |
(foo> MyObject)</syntaxhighlight> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
Line 1,493: | Line 1,493: | ||
regular methods can be called in these ways: |
regular methods can be called in these ways: |
||
< |
<syntaxhighlight lang=Pike>obj->method(); |
||
obj["method"](); |
obj["method"](); |
||
call_function(obj->method); |
call_function(obj->method); |
||
call_function(obj["method"]);</ |
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: |
||
< |
<syntaxhighlight lang=Pike>function func = obj->method; |
||
func();</ |
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: |
||
< |
<syntaxhighlight lang=Pike>module.func(); |
||
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. |
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}}== |
||
< |
<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,534: | Line 1,534: | ||
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;/</ |
END;/</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<syntaxhighlight lang=PowerShell>$Date = Get-Date |
||
$Date.AddDays( 1 ) |
$Date.AddDays( 1 ) |
||
[System.Math]::Sqrt( 2 )</ |
[System.Math]::Sqrt( 2 )</syntaxhighlight> |
||
=={{header|Processing}}== |
=={{header|Processing}}== |
||
< |
<syntaxhighlight lang=processing>// define a rudimentary class |
||
class HelloWorld |
class HelloWorld |
||
{ |
{ |
||
Line 1,562: | Line 1,562: | ||
// and call the instance method |
// and call the instance method |
||
hello.sayGoodbye();</ |
hello.sayGoodbye();</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang=python>class MyClass(object): |
||
@classmethod |
@classmethod |
||
def myClassMethod(self, x): |
def myClassMethod(self, x): |
||
Line 1,588: | Line 1,588: | ||
# 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)</ |
myInstance.myStaticMethod(someParameter)</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
Line 1,599: | Line 1,599: | ||
(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.) |
(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 |
[ immovable |
||
Line 1,669: | Line 1,669: | ||
say "Current value of mycounter: " |
say "Current value of mycounter: " |
||
report-counter mycounter echo cr cr</ |
report-counter mycounter echo cr cr</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,701: | Line 1,701: | ||
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. |
||
< |
<syntaxhighlight lang=racket>#lang racket/gui |
||
(define timer (new timer%)) |
(define timer (new timer%)) |
||
(send timer start 100)</ |
(send timer start 100)</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 1,710: | Line 1,710: | ||
{{works with|Rakudo|2015.12}} |
{{works with|Rakudo|2015.12}} |
||
=== Basic method calls === |
=== Basic method calls === |
||
<lang |
<syntaxhighlight lang=raku line>class Thing { |
||
method regular-example() { say 'I haz a method' } |
method regular-example() { say 'I haz a method' } |
||
Line 1,736: | Line 1,736: | ||
my $foo = new Thing: ; |
my $foo = new Thing: ; |
||
multi-example $thing: 42; |
multi-example $thing: 42; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=== Meta-operators === |
=== Meta-operators === |
||
Line 1,742: | Line 1,742: | ||
The <code>.</code> operator can be decorated with meta-operators. |
The <code>.</code> operator can be decorated with meta-operators. |
||
<lang |
<syntaxhighlight lang=raku line> |
||
my @array = <a z c d y>; |
my @array = <a z c d y>; |
||
@array .= sort; # short for @array = @array.sort; |
@array .= sort; # short for @array = @array.sort; |
||
say @array».uc; # uppercase all the strings: A C D Y Z |
say @array».uc; # uppercase all the strings: A C D Y Z |
||
</syntaxhighlight> |
|||
</lang> |
|||
=== Classless methods === |
=== Classless methods === |
||
Line 1,753: | Line 1,753: | ||
A method that is not in a class can be called by using the <code>&</code> sigil explicitly. |
A method that is not in a class can be called by using the <code>&</code> sigil explicitly. |
||
<lang |
<syntaxhighlight lang=raku line> |
||
my $object = "a string"; # Everything is an object. |
my $object = "a string"; # Everything is an object. |
||
my method example-method { |
my method example-method { |
||
Line 1,760: | Line 1,760: | ||
say $object.&example-method; # Outputs "This is a string." |
say $object.&example-method; # Outputs "This is a string." |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ring}}== |
=={{header|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> |
|||
< |
<syntaxhighlight lang=ring> |
||
o1 = new System.output.console |
o1 = new System.output.console |
||
o1.print("Hello World") |
o1.print("Hello World") |
||
Line 1,777: | Line 1,777: | ||
Func Print cText |
Func Print cText |
||
see cText + nl |
see cText + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang=ruby># Class method |
||
MyClass.some_method(some_parameter) |
MyClass.some_method(some_parameter) |
||
Line 1,795: | Line 1,795: | ||
# Calling a method with no parameters |
# Calling a method with no parameters |
||
my_instance.another_method</ |
my_instance.another_method</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang=rust>struct Foo; |
||
impl Foo { |
impl Foo { |
||
Line 1,828: | Line 1,828: | ||
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()); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<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,854: | Line 1,854: | ||
assert(n.memberVal == 3) |
assert(n.memberVal == 3) |
||
println("Successfully completed without error.") |
println("Successfully completed without error.") |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang=ruby>class MyClass { |
||
method foo(arg) { say arg } |
method foo(arg) { say arg } |
||
} |
} |
||
Line 1,879: | Line 1,879: | ||
# Alternatively, by asking for a method |
# Alternatively, by asking for a method |
||
instance.method(:foo)(arg);</ |
instance.method(:foo)(arg);</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
Line 1,885: | Line 1,885: | ||
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) |
||
< |
<syntaxhighlight lang=smalltalk>" Class " |
||
MyClass selector: someArgument . |
MyClass selector: someArgument . |
||
" or equivalently " |
" or equivalently " |
||
Line 1,901: | Line 1,901: | ||
" Binary (operator) message" |
" Binary (operator) message" |
||
myInstance + argument .</ |
myInstance + argument .</syntaxhighlight> |
||
Example for dynamic class determination: |
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: |
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</ |
foo perform: whichMessage</syntaxhighlight> |
||
or: |
or: |
||
< |
<syntaxhighlight lang=smalltalk>theMessage := ('handleFileType' , suffix) asSymbol. |
||
foo perform: theMessage.</ |
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). |
||
< |
<syntaxhighlight lang=smalltalk>[ |
||
foo perform: theMessage |
foo perform: theMessage |
||
] on: MessageNotUnderstood do:[ |
] on: MessageNotUnderstood do:[ |
||
Dialog information: 'sorry' |
Dialog information: 'sorry' |
||
]</ |
]</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> |
||
SomeClass { |
SomeClass { |
||
Line 1,943: | Line 1,943: | ||
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). |
||
< |
<syntaxhighlight lang=swift>// Class |
||
MyClass.method(someParameter) |
MyClass.method(someParameter) |
||
// or equivalently: |
// or equivalently: |
||
Line 1,957: | Line 1,957: | ||
// Method with multiple arguments |
// Method with multiple arguments |
||
myInstance.method(red:arg1, green:arg2, blue:arg3)</ |
myInstance.method(red:arg1, green:arg2, blue:arg3)</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<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</ |
$myInstance mthd someParameter</syntaxhighlight> |
||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
< |
<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"</ |
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,989: | Line 1,989: | ||
If myStr <> "" Then strTemp = myStr |
If myStr <> "" Then strTemp = myStr |
||
Debug.Print strTemp |
Debug.Print strTemp |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
In a "standard" Module, the call should be : |
In a "standard" Module, the call should be : |
||
< |
<syntaxhighlight lang=vb>Option Explicit |
||
Sub test() |
Sub test() |
||
Line 1,999: | Line 1,999: | ||
Obj.Method_1 |
Obj.Method_1 |
||
Obj.Method_2 |
Obj.Method_2 |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Hello to you |
<pre>Hello to you |
||
Line 2,008: | Line 2,008: | ||
=={{header|Wren}}== |
=={{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. |
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>class MyClass { |
||
construct new() {} |
construct new() {} |
||
method() { System.print("instance method called") } |
method() { System.print("instance method called") } |
||
Line 2,016: | Line 2,016: | ||
var mc = MyClass.new() |
var mc = MyClass.new() |
||
mc.method() |
mc.method() |
||
MyClass.method()</ |
MyClass.method()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,027: | Line 2,027: | ||
You can call object methods using two types of structures. Classes and Objects. |
You can call object methods using two types of structures. Classes and Objects. |
||
===Classes=== |
===Classes=== |
||
< |
<syntaxhighlight lang=XBS>class MyClass { |
||
construct=func(self,Props){ |
construct=func(self,Props){ |
||
self:Props=Props; |
self:Props=Props; |
||
Line 2,037: | Line 2,037: | ||
set Class = new MyClass with [{Name="MyClass Name"}]; |
set Class = new MyClass with [{Name="MyClass Name"}]; |
||
log(Class::GetProp("Name"));</ |
log(Class::GetProp("Name"));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,043: | Line 2,043: | ||
</pre> |
</pre> |
||
===Objects=== |
===Objects=== |
||
< |
<syntaxhighlight lang=XBS>set MyObj = { |
||
a=10; |
a=10; |
||
AddA=func(self,x){ |
AddA=func(self,x){ |
||
Line 2,050: | Line 2,050: | ||
} |
} |
||
log(MyObj::AddA(2));</ |
log(MyObj::AddA(2));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,058: | Line 2,058: | ||
=={{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. |
||
< |
<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 2,080: | Line 2,080: | ||
(DEFINE MY-INSTANCE (MY-CLASS 'NEW)) |
(DEFINE MY-INSTANCE (MY-CLASS 'NEW)) |
||
(MY-INSTANCE 'DO-SOMETHING-WITH 'BAR)</ |
(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 2,090: | Line 2,090: | ||
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. |
||
< |
<syntaxhighlight lang=zig>const assert = @import("std").debug.assert; |
||
pub const ID = struct { |
pub const ID = struct { |
||
Line 2,122: | Line 2,122: | ||
assert(person1.getAge() == 18); |
assert(person1.getAge() == 18); |
||
assert(ID.getAge(person2) == 20); |
assert(ID.getAge(person2) == 20); |
||
}</ |
}</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. |
||
< |
<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 2,136: | Line 2,136: | ||
D.f.isStatic //-->False |
D.f.isStatic //-->False |
||
class E{var v; fcn f{}} E.f.isStatic //-->True</ |
class E{var v; fcn f{}} E.f.isStatic //-->True</syntaxhighlight> |
||
<!-- Same omits as Classes page --> |
<!-- Same omits as Classes page --> |