开发者

How to share a variable across classes in Java, I tried static didn't work

开发者 https://www.devze.com 2023-02-10 17:59 出处:网络
class Testclass1has a variable, there is some execution which will change value of variable. Now in same package there is class Testclass2 . How will I access updated value(updated by Testclass1) of v

class Testclass1 has a variable, there is some execution which will change value of variable. Now in same package there is class Testclass2 . How will I access updated value(updated by Testclass1) of variable in Testclass2. tried this didn't work

Note: Testclass1 and Testclass2 are two separate files in same package, I tried to run class1 first in eclipse and then class2. But class2 printed 0;

public class Testclass1 {
    public static int value;
    public static void main(String[]args)
    {
        Testclass1.value=9;
        System.out.pri开发者_Python百科ntln(value);
    }
}

----------------

public class Testclass2 {
    public static void main(String[]args)
    {
        System.out.println(Testclass1.value);
    }
}


Your problem is not sharing values across classes, you want to share values across subsequent program executions. To do that, you need to persist the value somewhere. Typically, files or databases are used for that.


You have to write something like this in your First Program

public class Testclass1 {
    public static int value;
    public static void main(String[]args)
    {
        try
        {
            Testclass1.value=9;
            System.out.println(value);
            new FileWriter("test.txt", false).append(String.valueOf(value));
        }
        catch(Exception ex)
        {
            //do something
        }            
    }
}

Then invoke your second program after this modification:

public class Testclass2 {
    public static void main(String[]args)
    {
        try
        {
            Scanner s = new Scanner(new File("test.txt");
            Testclass1.value = s.nextInt();
            System.out.println(Testclass1.value);
        }
        catch(Exception ex)
        {
            //do something
        }
    }
}

Couple of thing to take care:

  1. Make sure you run the programs from the same directory.
  2. You must have the .class File of TestClass1 in that directory before you run TestClass2.
  3. Also it would be a good practice to close the FileWriter once you are done.


If you can get main method of TestClass1 to execute, it will work. Reason it is not working, is because main method of TestClass1 never executed and so the value was never set.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号