Jump to content

Call an object method: Difference between revisions

→‎{{header|Factor}}: change a class to a regular tuple; makes for a better example
(Add Factor example)
(→‎{{header|Factor}}: change a class to a regular tuple; makes for a better example)
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.
 
<lang factor>!USING: Defineaccessors someio classes.kernel literals math sequences ;
IN: rosetta-code.call-a-method
 
! Define some classes.
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
Line 318 ⟶ 324:
! Define methods in speak which specialize on various classes.
M: dog speak drop "Woof!" print ;
M: cat speak dropsassiness>> 0.5 > "Hiss!" "Meow!" ? print ;
M: object speak drop "I don't know how to speak!" print ;
 
! Place threesome objects of differentvarious classes onin thea data stacksequence.
${ dog 0.75 <cat> 0.1 <cat> 10 }
! Call speak, a method, just like any other word.
[ speak ] tri@each </lang>
{{out}}
<pre>
Woof!
Hiss!
Meow!
I don't know how to speak!
1,827

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.