Accessing program elements

It took me some time to get used to the different cases that exist, when we have both static and instance versions of both methods and variables

Accessing static variables in a static method

class: Clock
static int seconds

: incrementSeconds  ( int diff -- )
     seconds diff + is seconds   ;

: main   ( string [] args -- )
     10 incrementSeconds  seconds .  ;

Accessing static variables in an instance method

class: Clock

static int seconds

i: incrementSeconds  ( int diff -- )
      seconds diff + is seconds   ;

Accessing instance variables in a static method 

class: Clock

int seconds
static Clock myClock

: incrementSeconds  ( int diff -- )
     myClock seconds diff +  myClock is seconds   ;

: main   ( string [] args -- )
     new myclock ()       
     10 incrementSeconds  myClock seconds .  ; 

I use a class variable to store the object reference.  new myClock () creates an instance of Clock and stores the reference in the field myClock.

Accessing instance variables in an instance method 

class: Clock

int seconds

i: incrementSeconds  ( int diff -- )
      seconds diff + is seconds  ;
   
: main   ( string [] args -- )
     clock myClock new myClock () 
     10 myClock incrementSeconds  myClock seconds .  ;

new myClock () creates an instance of Clock and stores the reference in the local variable myClock.




1998-2013 Wolf Wejgaard