I'm trying to understand scope of variables and how to use variables initialised from one class and use them in another but coming up stuck in my understanding.
I have a class Test1
defined as follows:
public class Test1 {
private int x;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
I am calling this class in my main
:
public class Main {
public static void main(String[] args) {
Test1 test1 = new Test1();
Test2 test2 = new Test2();
test1.setX(33);
int y = test1.getX();
System.out.print(y); // prints 33
test2.testing(); // method outputs 0 instead of showing the value of X
}
}
I have another class Test2
:
public class Test2 {
public static void testing() {
Test1 test1 = new Test1();
int val = test1.getX();
System.out.print(val);
}
}
If I then call the method in my main, the value of val
is showing 0
rather than 33. How can I access the value in memory of getX()
in another class?
Thanks