wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes static variable?! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static variable?!" Watch "static variable?!" New topic
Author

static variable?!

vijay gardiner
Greenhorn

Joined: Jan 26, 2002
Posts: 14
I've a program like :
public class Boxdemo {
int x = 10;
public static void main ( String args[] ) {
Boxdemo nt = new Boxdemo() ;
nt.x = 20;
System.out.println ("nt.x" + nt.x);
Boxdemo nt1 = new Boxdemo();
nt1.x = 30;
System.out.println ("nt.x" + nt.x);
System.out.println ("nt1.x" + nt1.x);
}
}
this program passes the compilation, but i've another program like :
public class Boxdemo {
int x = 10;
public static void main ( String args[] ) {
Boxdemo nt = new Boxdemo() ;
Boxdemo.x = 20;
System.out.println ("nt.x" + nt.x);
Boxdemo nt1 = new Boxdemo();
nt1.x = 30;
System.out.println ("nt.x" + nt.x);
System.out.println ("nt1.x" + nt1.x);
}
}
But this program fails in compilation : saying not-static variable cannot be accessed in a static context.
If the second program fails, I thought the first program also should fail, b'cos I'm accessing the same variable 'x' under the static main method().
Can anyone why i get the error message?
Thanx,
Vijay
Vijay Albuquerque
Ranch Hand

Joined: Feb 17, 2002
Posts: 42
The second program attempts to access the instance variable 'x' as a static variable.
>> Boxdemo.x = 20;
An instance variable cannot be referred to directly by qualifying with a class name.
Hence the compilation error !!


Vijay Albuquerque
SCJP 1.4, SCWCD 1.3
vijay gardiner
Greenhorn

Joined: Jan 26, 2002
Posts: 14
Hi,
As I'm a beginner, I'm not still clear with ur explaination.....you've told "The second program attempts to access the instance variable 'x' as a static variable"
I don't understand the part "static variable" in ur explaination. A\as I'm accessing the instance variable x directly by the class name, do you mean that java will interpret that as a 'static variable', and the how come, if i access the same variable x using an instance of that class "nt", java doesn't say any error messages??
Please, can you explain??
Vijay
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

A variable that is declared 'static' means that the variable is available to the class as a whole, and not just a single instance of that class (in your example, the instance nt). So variables that are declared static are available through the class name (and confusingly, also through an instance name).Both of those assignments will work, because x is declared static.

So... because your x variable is not declared static, it is ONLY available through an *instance* of the class, and not through a 'static' reference. That is why your second program fails.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static variable?!