Call an object method: Difference between revisions
Content added Content deleted
No edit summary |
(Add Factor example) |
||
Line 304: | Line 304: | ||
IO.puts(obj |> ObjectCall.concat("Hello ", "World!")) |
IO.puts(obj |> ObjectCall.concat("Hello ", "World!")) |
||
</lang> |
</lang> |
||
=={{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. |
|||
<lang factor>! Define some classes. |
|||
SINGLETON: dog |
|||
SINGLETON: cat |
|||
! Define a generic word that dispatches on the object at the top |
|||
! of the data stack. |
|||
GENERIC: speak ( obj -- ) |
|||
! Define methods in speak which specialize on various classes. |
|||
M: dog speak drop "Woof!" print ; |
|||
M: cat speak drop "Meow!" print ; |
|||
M: object speak drop "I don't know how to speak!" print ; |
|||
! Place three objects of different classes on the data stack. |
|||
dog cat 10 |
|||
! Call speak, a method, just like any other word. |
|||
[ speak ] tri@</lang> |
|||
{{out}} |
|||
<pre> |
|||
Woof! |
|||
Meow! |
|||
I don't know how to speak! |
|||
</pre> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |