• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variable scope

 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a class I have declared a variable at the top.

My understanding is that this variable is then available to all methods within the class.

However in a method at the end of the class I am finding that the variable declared at the top is not available.

Why would this happen? Is my understanding, that a variable declared at the top of a class is available to all methods within the class NOT correct?

Does this mean my understanding is incorrect?
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is the variable static or non-static? If you do not use the keyword 'static', the variable is only available to particular instances of the object (ones created with the new keyword). If you are attempting to access the variable from a method marked 'static' (i.e. public static void main), you must label the variable at the top 'static' as well.

static int number;
[ November 07, 2004: Message edited by: Nick George ]
 
Jimmy Die
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,


Make sure that the decleration is outside of constructors and methods, you can initilize them inside constructors and methods but if you declair them then inside you can only use them inside.


ie.

class SomeClass {

public SomeClass() {
int j = 0; /// can only be used inside the constructor

}

}

class NewSomeClass{

int j;

public NewSomeClass{) {
j = 0; // because it was declaired outside the constructor then you can
// use it outside... Variable scope!!!

}

}
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please post the specific code. Trying to summarize often loses important details and we have to guess what the problem is. Even if the cause of the problem isn't obvious to you, it might be obvious to someone here if we can see your actual code.

Be sure to use UBB CODE tags to preserve your formatting. There are buttons below text box where you edit a message that can help with this. If you take the small amount of time to do this, your code will be much more readable and we will be able to help you more easily.

Thanks,

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic