Sharing varibles thought a class.

Custom / CUSTOM
January 23, 2010 at 05:37:56
Specs: Windows XP, 8g
Hi all, I've recently started teaching myself JAVA but I have had a few problems. I would like to be able to create a variable in one method and have it accessible from one if not all other methods in that class.

An example of the code I have is

public void createvar(){
int house, pop, houserd;
house = 1;
houserd = 0;
pop = house * (10 + houserd);
}

public void popcount(){
pop = house * (10 + houserd);
}


See More: Sharing varibles thought a class.

Report •

#1
January 23, 2010 at 06:06:25
My class is

class plan2{

....

}


Report •

#2
January 23, 2010 at 11:47:25
I would like to be able to create a variable in one method and have it accessible from one if not all other methods in that class.
Then define it in the class, and not the method.

Report •

#3
January 23, 2010 at 17:58:45
I am unsure how to do so, and upon Google I found no direct
answers. Could you please explain how to do so?

Report •

Related Solutions

#4
January 23, 2010 at 19:21:45
class plan2 {
  int someInt;
  public void createvar() {
      .      .      .      .      .
}


Report •

#5
January 23, 2010 at 19:24:21
I think I got it, this is what I put before the previous code, then
removed the creation of the variables in createvar. I think I have it
right now thanks. If you have any input please feel free to post it.

public static int pop, house, houserd;


Report •

#6
January 23, 2010 at 23:04:05
Be careful; if you declare a class variable static, it's shared between every instance of that class.

Report •

#7
January 24, 2010 at 01:46:42
So if its a multi user program they all access and change the
same variable?

Report •

#8
January 24, 2010 at 10:23:28
No. I think you need to step back, and learn, at the very least, Java's concept of scope and its general object model.

Report •

Ask Question