Call an object method: Difference between revisions

Content added Content deleted
m (omit c)
(added go)
Line 3: Line 3:
[[Category:Encyclopedia]]
[[Category:Encyclopedia]]


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


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


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

=={{header|Go}}==
<lang go>type Foo int // some custom type

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

// method on the pointer to the type; can be called on pointers
func (*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>


=={{header|J}}==
=={{header|J}}==