Call an object method

From Rosetta Code
Revision as of 18:31, 11 August 2012 by rosettacode>Bearophile (+ D entry)
Call an object method is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

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

Works with: AutoHotkey_L

(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

This example is in need of improvement:

Add runnable example.

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

<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.

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.

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. <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);

  1. Equivalently using a class name

my $foo = 'MyClass'; $foo->classMethod($someParameter);


  1. Instance method

$myInstance->method($someParameter);

  1. Calling a method with no parameters

$myInstance->anotherMethod;

  1. Class and instance method calls are made behind the scenes by getting the function from
  2. 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()

  1. Instance method

myInstance.myMethod(someParameter)

  1. A method can also be retrieved as an attribute from the class, and then explicitly called on an instance:

MyClass.myMethod(myInstance, someParameter)


  1. Class or static methods

MyClass.myClassMethod(someParameter) MyClass.myStaticMethod(someParameter)

  1. 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>

Ruby

<lang ruby># Class method MyClass.some_method(some_parameter)

  1. Class may be computed at runtime

foo = MyClass foo.some_method(some_parameter)


  1. Instance method

my_instance.method(some_parameter)

  1. The parentheses are optional

my_instance.method some_parameter

  1. 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 there are no "static" methods. <lang smalltalk>" Class " MyClass method:someParameter . " or equivalently " foo := MyClass . foo method:someParameter .

" Instance " myInstance method:someParameter .

" Method with multiple arguments " myInstance methodWithRed:arg1 green:arg2 blue:arg3 .

" Method with no arguments " myInstance method .

" Operator method " myInstance + somethingElse .</lang>

Tcl

<lang tcl>package require Tcl 8.6

  1. "Static" (on class object)

MyClass mthd someParameter

  1. Instance

$myInstance mthd someParameter</lang>