| Author |
static explaination?!
|
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); } } 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 ("Boxdemo.x" + Boxdemo.x); } } But this program fails in compilation : saying non-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?
|
 |
Maciej Kolodziej
Greenhorn
Joined: Feb 11, 2002
Posts: 26
|
|
In this fragment You're creating an object (instance) of Boxdemo class and than accessing variable x in this specific object (nt.x). So everything is fine and it compiles well. Here You also create this object and also call it nt. But than, You don't access this object's x variable, instead You try to access Boxdemo _class_ x variable. This can't be done, since x is not static. That's why You get this error. And it's not because main is static, but because x is not static in Boxdemo. Now You must remember what a static variable is. It's variable common for the class. So if You would write: Than Your code would compile without errors. I recommend some closer look at static methods/variables in java: Java tutorial
|
MK
|
 |
vijay gardiner
Greenhorn
Joined: Jan 26, 2002
Posts: 14
|
|
|
thanx! that was useful!
|
 |
 |
|
|
subject: static explaination?!
|
|
|