Call an object method: Difference between revisions
Content added Content deleted
(Add Factor example) |
(→{{header|Factor}}: change a class to a regular tuple; makes for a better example) |
||
Line 308: | Line 308: | ||
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. |
||
<lang factor> |
<lang factor>USING: accessors io kernel literals math sequences ; |
||
IN: rosetta-code.call-a-method |
|||
! Define some classes. |
|||
SINGLETON: dog |
SINGLETON: dog |
||
TUPLE: cat sassiness ; |
|||
SINGLETON: cat |
|||
! Define a constructor for cat. |
|||
C: <cat> cat |
|||
! Define a generic word that dispatches on the object at the top |
! Define a generic word that dispatches on the object at the top |
||
Line 318: | Line 324: | ||
! Define methods in speak which specialize on various classes. |
! Define methods in speak which specialize on various classes. |
||
M: dog speak drop "Woof!" print ; |
M: dog speak drop "Woof!" print ; |
||
M: cat speak |
M: cat speak sassiness>> 0.5 > "Hiss!" "Meow!" ? print ; |
||
M: object speak drop "I don't know how to speak!" print ; |
M: object speak drop "I don't know how to speak!" print ; |
||
! Place |
! Place some objects of various classes in a sequence. |
||
dog cat 10 |
${ dog 0.75 <cat> 0.1 <cat> 10 } |
||
! Call speak, a method, just like any other word. |
! Call speak, a method, just like any other word. |
||
[ speak ] |
[ speak ] each </lang> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Woof! |
Woof! |
||
Hiss! |
|||
Meow! |
Meow! |
||
I don't know how to speak! |
I don't know how to speak! |