Call an object method: Difference between revisions
Added Forth (4tH) version |
Add Racket entry |
||
Line 439: | Line 439: | ||
myInstance.myClassMethod(someParameter) |
myInstance.myClassMethod(someParameter) |
||
myInstance.myStaticMethod(someParameter)</lang> |
myInstance.myStaticMethod(someParameter)</lang> |
||
=={{header|Racket}}== |
|||
The following snippet shows a call to the <tt>start</tt> method of the <tt>timer%</tt> class. |
|||
<lang racket>#lang racket/gui |
|||
(define timer (new timer%)) |
|||
(send timer start 100)</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
Revision as of 04:01, 28 March 2013
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
ActionScript
<lang actionscript>// Static MyClass.method(someParameter);
// Instance myInstance.method(someParameter);</lang>
AutoHotkey
(AutoHotkey Basic does not have classes) <lang AHK>class myClass { Method(someParameter){ MsgBox % SomeParameter } }
myClass.method("hi") myInstance := new myClass myInstance.Method("bye")</lang>
C++
<lang cpp>// Static MyClass::method(someParameter);
// Instance myInstance.method(someParameter);</lang>
D
<lang d>struct Cat {
static int staticMethod() { return 2; }
string dynamicMethod() { // Never virtual. return "Mew!"; }
}
class Dog {
static int staticMethod() { return 5; }
string dynamicMethod() { // Virtual method. return "Woof!"; }
}
void main() {
// Static methods calls: assert(Cat.staticMethod() == 2); assert(Dog.staticMethod() == 5);
Cat c; // This is a value on the stack. Dog d; // This is just a reference, set to null.
// Other static method calls, discouraged: assert(c.staticMethod() == 2); assert(d.staticMethod() == 5);
// Instance method calls: assert(c.dynamicMethod() == "Mew!"); d = new Dog; assert(d.dynamicMethod() == "Woof!");
}</lang>
E
A method call in E has the syntax recipient.verb(arg1, arg2, ...)
, where recipient is an expression, verb is an identifier (or a string literal preceded by ::
), and argN are expressions.
<lang e>someObject.someMethod(someParameter)</lang>
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.
Forth
There are numerous, mutually incompatible object oriented frameworks for Forth. This one works with the FOOS preprocessor extension of 4tH. <lang forth>include lib/compare.4th include 4pp/lib/foos.4pp
[ASSERT] \ enable assertions
- Cat
class method: dynamicCat \ virtual method end-class {
:static staticCat { 2 } ; \ static method :method { s" Mew!" } ; defines dynamicCat } \ for unrelated classes,
- \ method names have to differ
- Dog
class method: dynamicDog \ virtual method end-class {
:static staticDog { 5 } ; :method { s" Woof!" } ; defines dynamicDog } \ for unrelated classes,
- \ method names have to differ
static Cat c \ create two static objects static Dog d
- main
assert( class -> staticCat 2 = ) \ check for valid method return assert( class -> staticDog 5 = ) \ of a static method
assert( c -> staticCat 2 = ) \ check for valid method return assert( d -> staticDog 5 = ) \ of a static method
assert( c => dynamicCat s" Mew!" compare 0= ) assert( d => dynamicDog s" Woof!" compare 0= )
- \ same for dynamic methods
main</lang>
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. <lang go>type Foo int // some custom type
// method on the type itself; can be called on that type or its pointer func (self Foo) ValueMethod(x int) { }
// method on the pointer to the type; can be called on pointers func (self *Foo) PointerMethod(x int) { }
var myValue Foo
var myPointer *Foo = new(Foo)
// Calling value method on value myValue.ValueMethod(someParameter) // Calling pointer method on pointer myPointer.PointerMethod(someParameter)
// Value methods can always be called on pointers // equivalent to (*myPointer).ValueMethod(someParameter) myPointer.ValueMethod(someParameter)
// In a special case, pointer methods can be called on values that are addressable (i.e. lvalues) // equivalent to (&myValue).PointerMethod(someParameter) myValue.PointerMethod(someParameter)
// You can get the method out of the type as a function, and then explicitly call it on the object Foo.ValueMethod(myValue, someParameter) (*Foo).PointerMethod(myPointer, someParameter) (*Foo).ValueMethod(myPointer, someParameter)</lang> 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: <lang go>package box
import "sync/atomic"
var sn uint32
type box struct {
Contents string secret uint32
}
func New() (b *box) {
b = &box{secret: atomic.AddUint32(&sn, 1)} switch sn { case 1: b.Contents = "rabbit" case 2: b.Contents = "rock" } return
}
func (b *box) TellSecret() uint32 {
return b.secret
}
func Count() uint32 {
return atomic.LoadUint32(&sn)
}</lang> Example use: <lang go>package main
import "box"
func main() {
// Call constructor. Technically it's just an exported function, // but it's a Go idiom to naming a function New that serves the purpose // of a constructor. b := box.New()
// Call instance method. In Go terms, simply a method. b.TellSecret() // Call class method. In Go terms, another exported function. box.Count()
}</lang>
Icon and Unicon
In Unicon all procedures and methods are dynamically invoked at run-time. The normal method of invoking a method is with instances of its class. While it is technically possible to call a method without having an instance it requires knowledge of the underlying translation of methods and classes to procedures and is somewhat unusual. <lang unicon>procedure main()
foo_m1() # equivalent of class method, not normally used bar := foo() # create instance bar.m2() # call method m2 with self=bar
end
class foo(cp1,cp2)
method m1(m1p1,m1p2) local ml1 static ms1 ml1 := m1p1 # do something return end method m2(m2p1) # do something else return end
initially
L := [cp1]
end</lang> Note: Icon cannot translate code with objects. It may be possible for Icon to translate code preprocessed by Unicon if no other Unicon extensions are used.
J
Note: In some languages "everything is an object". This is not the case in J. In J, non-trivial objects will contain arrays. This is a relatively deep issue, beyond the scope of this page, except that: method invocations are relatively rare, in J.
All method invocations must contain two underline characters in J:
Static:
<lang j>methodName_className_ parameters</lang>
and, given an object instance reference:
<lang j>objectReference=: conew 'className'</lang>
an instance invocation could be:
<lang j>methodName__objectReference parameters</lang>
Note that J also supports infix notation when using methods. In this case, there will be a second parameter list, on the left of the method reference.
<lang j>parameters methodName_className_ parameters</lang> or <lang j>parameters methodName__objectReference parameters</lang>
These variations might be useful when building combining words that need to refer to two different kinds of things. But mostly it's to be consistent with the rest of the language.
Finally, note that static methods can be referred to using the same notation as instance methods -- in this case you must have a reference to the class name:
<lang j>classReference=: <'className' methodName__classReference parameters</lang>
This might be useful when you are working with a variety of classes which share a common structure.
You can also refer to a dynamic method in the same fashion that you use to refer to a instance method -- in this case you must know the object name (which is a number). For example, to refer to a method on object 123
<lang j>methodName_123_ parameters</lang>
This last case can be useful when debugging.
Java
Static methods in Java are usually called by using the dot operator on a class name: <lang java>ClassWithStaticMethod.staticMethodName(argument1, argument2);//for methods with no arguments, use empty parentheses</lang> Instance methods are called by using the dot operator on an instance: <lang java>ClassWithMethod varName = new ClassWithMethod(); varName.methodName(argument1, argument2); //or new ClassWithMethod().methodName(argument1, argument2);</lang>
Instance methods may not be called on references whose value is null
(throws a NullPointerException
).
Note: Static methods can also be called using the dot syntax on a reference to an instance, looking identical to an instance method call, but this is highly discouraged, and compilers usually complain about that (with a warning, not a failed compilation). The reason for this is that such a call is actually equivalent to a static method call on the static (compile-time) type of the reference in the source code. That means the runtime value of that reference is actually irrelevant, and the reference may be null
or be a reference to an instance of a subclass, the compiler will still make it a call to the static method based on the class of the value at compile-time (i.e. inheritance does not apply; the method call is not resolved at runtime).
This means that there is no benefit to making a static method call this way, because one can make the call based on the static type that is already known from looking at the code when it is written. Furthermore, such a call may lead to serious pitfalls, leading one to believe that changing the object that it is called on could change the behavior. For example, a common snippet to sleep the thread for 1 second is the following: Thread.currentThread().sleep(1000);
. However, since .sleep()
is actually a static method, the compiler replaces it with Thread.sleep(1000);
(since Thread.currentThread()
has a return type of Thread
). This makes it clear that the thread that is put to sleep is not under the user's control. However, written as Thread.currentThread().sleep(1000);
, it may lead one to falsely believe it to be possible to sleep another thread by doing someOtherThread.sleep(1000);
when in fact such a statement would also sleep the current thread.
NetRexx
Like Java, static methods in NetRexx are called by using the dot operator on a class name: <lang NetRexx>SomeClass.staticMethod()</lang> Instance methods are called by using the dot operator on an instance: <lang 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</lang>
Objeck
<lang objeck> ClassName->some_function(); # call class function instance->some_method(); # call instance method </lang> Objeck uses the same syntax for instance and class method calls. In Objeck, functions are the equivalent of public static methods.
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). <lang objc>// Class [MyClass method:someParameter]; // or equivalently: id foo = [MyClass class]; [foo method:someParameter];
// Instance [myInstance method:someParameter];
// Method with multiple arguments [myInstance methodWithRed:arg1 green:arg2 blue:arg3];
// Method with no arguments [myInstance method];</lang>
OCaml
We can only call the method of an instantiated object:
<lang ocaml>my_obj#my_meth params</lang>
Perl
<lang perl># Class method MyClass->classMethod($someParameter);
- Equivalently using a class name
my $foo = 'MyClass'; $foo->classMethod($someParameter);
- Instance method
$myInstance->method($someParameter);
- Calling a method with no parameters
$myInstance->anotherMethod;
- Class and instance method calls are made behind the scenes by getting the function from
- the package and calling it on the class name or object reference explicitly
MyClass::classMethod('MyClass', $someParameter); MyClass::method($myInstance, $someParameter);</lang>
Perl 6
<lang perl6>ClassName.methodname(); # call class method $instance.methodname(); # call instance method</lang> Note that, unlike in Perl 5, class names are type objects, not strings. (Type objects are typed variants of the undefined value in Perl 6.)
PHP
<lang php>// Static method MyClass::method($someParameter); // In PHP 5.3+, static method can be called on a string of the class name $foo = 'MyClass'; $foo::method($someParameter);
// Instance method
$myInstance->method($someParameter);</lang>
PicoLisp
Method invocation is syntactically equivalent to normal function calls. Method names have a trailing '>' by convention. <lang PicoLisp>(foo> MyClass) (foo> MyObject)</lang>
Pike
Pike does not have static methods. (the static
modifier in Pike is similar to protected
in C++).
regular methods can be called in these ways:
<lang Pike>obj->method();
obj["method"]();
call_function(obj->method);
call_function(obj["method"]);</lang>
call_function()
is rarely used anymore.
because ()
is actually an operator that is applied to a function reference, the following is also possible:
<lang Pike>function func = obj->method;
func();</lang>
as alternative to static function, modules are used. a module is essentially a static class. a function in a module can be called like this:
<lang Pike>module.func();
module["func"]();</lang>
it should be noted that module.func
is resolved at compile time while module["func"]
is resolved at runtime.
PL/SQL
<lang PL/SQL>create or replace TYPE myClass AS OBJECT (
-- A class needs at least one member even though we don't use it dummy NUMBER, STATIC FUNCTION static_method RETURN VARCHAR2, MEMBER FUNCTION instance_method RETURN VARCHAR2
); / CREATE OR REPLACE TYPE BODY myClass AS
STATIC FUNCTION static_method RETURN VARCHAR2 IS BEGIN RETURN 'Called myClass.static_method'; END static_method; MEMBER FUNCTION instance_method RETURN VARCHAR2 IS BEGIN RETURN 'Called myClass.instance_method'; END instance_method;
END; /
DECLARE
myInstance myClass;
BEGIN
myInstance := myClass(null); DBMS_OUTPUT.put_line( myClass.static_method() ); DBMS_OUTPUT.put_line( myInstance.instance_method() );
END; /</lang>
Python
<lang python>class MyClass(object): @classmethod def myClassMethod(self, x): pass @staticmethod def myStaticMethod(x): pass def myMethod(self, x): return 42 + x
myInstance = MyClass()
- Instance method
myInstance.myMethod(someParameter)
- A method can also be retrieved as an attribute from the class, and then explicitly called on an instance:
MyClass.myMethod(myInstance, someParameter)
- Class or static methods
MyClass.myClassMethod(someParameter) MyClass.myStaticMethod(someParameter)
- You can also call class or static methods on an instance, which will simply call it on the instance's class
myInstance.myClassMethod(someParameter) myInstance.myStaticMethod(someParameter)</lang>
Racket
The following snippet shows a call to the start method of the timer% class.
<lang racket>#lang racket/gui
(define timer (new timer%)) (send timer start 100)</lang>
Ruby
<lang ruby># Class method MyClass.some_method(some_parameter)
- Class may be computed at runtime
foo = MyClass foo.some_method(some_parameter)
- Instance method
my_instance.method(some_parameter)
- The parentheses are optional
my_instance.method some_parameter
- Calling a method with no parameters
my_instance.another_method</lang>
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)
<lang smalltalk>" Class " MyClass selector: someArgument . " or equivalently " foo := MyClass . foo selector: someArgument.
" Instance " myInstance selector: someArgument.
" Message with multiple arguments " myInstance fooWithRed:arg1 green:arg2 blue:arg3 .
" Message with no arguments " myInstance selector.
" Binary (operator) message" myInstance + argument .</lang>
Example for dynamic class determination:
<lang smalltalk>
theCar := (someCondition ifTrue:[ Ford ] ifFalse: [ Jaguar ]) new.</lang>
Message names (selectors) can be chosen or constructed dynamically at runtime. For example: <lang smalltalk> whichMessage := #( #'red' #'green' #'blue') at: computedIndex. foo perform: whichMessage</lang>
or:
<lang smalltalk> theMessage := ('handleFileType' , suffix) asSymbol. foo perform: theMessage.</lang> 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). <lang smalltalk>[
foo perform: theMessage
] on: MessageNotUnderstood do:[
Dialog information: 'sorry'
]</lang>
Tcl
<lang tcl>package require Tcl 8.6
- "Static" (on class object)
MyClass mthd someParameter
- Instance
$myInstance mthd someParameter</lang>
- Programming Tasks
- Basic language learning
- Object oriented
- Encyclopedia
- ActionScript
- AutoHotkey
- C++
- D
- E
- E examples needing attention
- Examples needing attention
- Forth
- Go
- Unicon
- J
- Java
- NetRexx
- Objeck
- Objective-C
- OCaml
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PL/SQL
- Python
- Racket
- Ruby
- Smalltalk
- Tcl
- AWK/Omit
- BASIC/Omit
- Fortran/Omit
- GUISS/Omit
- Locomotive Basic/Omit
- M4/Omit
- Mathematica/Omit
- Metafont/Omit
- Octave/Omit
- PARI/GP/Omit
- TI-89 BASIC/Omit
- Retro/Omit
- UNIX Shell/Omit
- ZX Spectrum Basic/Omit
- C/Omit