-1

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.

Luke
  • 3
  • 3
  • 1
    Just a pedantic point - since others have ably described your issue. Luke, in general you want to AVOID public members like you've used, because it becomes very hard to encapsulate them later with business logic (validation etc), and to handle thread safety. Use getters/setters unless you are very sure the class is always going to be this primitive, always used in a single thread, and not used by too many classes. Just a pointer. – MJB May 01 '11 at 04:22

2 Answers2

1

I'm not sure how you refer to a class like dostuff(); and QandA();[there has to be compilation errors for those] but just keep in mind to create just one Command instance and pass the same instance around. In your case, every time you create an instance of QandA, a Command instance is created with it's torch field set to 1

Bala R
  • 107,317
  • 23
  • 199
  • 210
1

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).

Steve B.
  • 55,454
  • 12
  • 93
  • 132