Monday, April 13, 2009

JAVA: why static variables cannot be referenced from non-static context

hi guys, this is rahul

i have always been wondering on properties of the key-word static !!!

i`m really enthralled on discoveries that i make while playing with the language, that`s how its should be learnt;

this article deal about why in java programming, static variables cannot be accessed from non-static context;

consider the following code:

class Static
static int x=20;
int y=40;
class TestStatic extends Static
public static void main(String[] ar){

//Static x=new Static();

the above code works fine, because we have accessed static members from static context.

static means, one can access the member without having to create the class object(only classname.staticvariablename will do)

instance variables(variables declared in class) are created ONLY IF the object for the class is created.

Static methods and members are at the class level and not instance or the object level.

so that means they can't access instance level methods/members.

for example,

class Example
int x; // non-static integer 'x'.

static void foo()
return x+4;

In above example, unless an object of Example is created, the variable "x" doesn't exist.
But still u can call method foo() using BUT WAIT !!! What is 'x' in this case??
it is not static, it is an instance variable and is initialized only if class object is created
Same thing happens with static methods.
Therefore you can access non-static members from within static context.

No comments:

Post a Comment