In Java can I keep a variable from one method to a next, and across Classes?
I am trying to get a variable from Commands, modify it in QandA and expect it to persist until i modify it again.
public class Commands
{
int torch = 1;
}
_____________
public class QandA
{
Dostuff d = new Dostuff
Commands a = new Commands();
public void torch
{
System.out.println("Torch = " + torch);
a.torch = 2;
System.out.println("Torch = " + torch);
d.dostuff();
}
public class dostuff
{
public void dostuff()
{
// User imput is gathered here etc etc.
QandA();
}
}
So I would expect output to be (a loop of)
Torch = 1
Torch = 2
Torch = 2
Torch = 2
Torch = 2
Torch = 2
After 3 Cycles. But what it does is.
Torch = 1
Torch = 2
Torch = 1
Torch = 2
Torch = 1
Torch = 2
After three cycles.
Please help.
There's no problem with persisting data, however you have to be conscious of where you create and save it.
In your case you are declaring "torch" inside the Command class scope, as a member of Command initialized to "1" ( I think - the syntax is a bit funny). Therefore every time you declare "new Command()" you're starting with a new "torch" variable == 1.
You can declare the "torch" as static, meaning it's shared for all Command instances, and then it will behave as you want, as it won't be getting reset every time the constructor is called (provided you're not setting it to 1 inside the constructor).