Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static field

 
sura watthana
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

could somebody give me a reason why static variable of a class is accessible from either non-static method or constructor.

thanks

Sura
 
Doyle Matt
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static things (static method and variables) are accessible in both non-static and static methods because static exists in the class. you do not need to create an instance of the class just to use that static variable/method.
 
Arnab karmakar
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi sura,

static variable dont need any instantiation and so they get allocated in memory before anything else. This u can say just similar to codes in C. like this

# define val 10

They could be accessed from any class, either static or non-static


arnab
 
Doyle Matt
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe the #define attribute of C is a poor example for the static keyword in java. I think #define will make a compile-time constant whereas static [value] can be change during run time.

Please correct me if i'm wrong.
 
Louie van Bommel
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static variables are initialized when the class is loaded. A class gets loaded the first time it is referenced in the program. Therefore static variables are accessible to any instance method or constructor because they are already initialized before any instance of an object is created.

Instance variables are initialized during the creation of an instance (an object).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic