File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static field Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static field" Watch "static field" New topic

static field

sura watthana
Ranch Hand

Joined: Sep 13, 2004
Posts: 77

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


Doyle Matt
Ranch Hand

Joined: Jul 05, 2004
Posts: 76
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.

SCJP 1.4
Arnab karmakar
Ranch Hand

Joined: Oct 04, 2004
Posts: 46
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

Doyle Matt
Ranch Hand

Joined: Jul 05, 2004
Posts: 76
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

Joined: Aug 17, 2004
Posts: 76
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).
I agree. Here's the link:
subject: static field
It's not a secret anymore!