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:
- Make sure you run the programs from the same directory.
- You must have the .class File of TestClass1 in that directory before you run TestClass2.
- 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.
精彩评论