How to split a variable between classes in Java, I tried static did not work

The Testclass1 class has a variable, some execution is performed that will change the value of the variable. Now in the same package is the class Testclass2. How to access the updated value (updated Testclass1) of a variable in Testclass2. tried it didn't work

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

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

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

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

, , . - . , .

+9

-

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
        }            
    }
}

:

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
        }
    }
}

, :

  • , .
  • TestClass2 .class TestClass1 .
  • FileWriter, .
+1

main TestClass1 , . , , , main TestClass1 , .

0
source

Source: https://habr.com/ru/post/1791801/


All Articles