Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static explaination?!

 
vijay gardiner
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
vijay gardiner
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx! that was useful!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic