Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static variable?!

 
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);
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
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 gardiner
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic