I am trying to change private variables in a method and then access them with a getter method in the main method (as shown below), but when I get the private variable in the main method it is always 0. How can I set a private variable in a method other than the main, but still be able to access that variable in the main method?
public class Example {
private int testNumber;
public static void main(String[] args) {
Example tester = new Example();
System.out.println(tester.getTestNumber());
tester.TheTestExample();
System.out.println(tester.getTestNumber());
}
public int getTestNumber(){
return testNumber;
}
public void setTestNumber(int x){
this.testNumber = x;
}
public void TheTestExample(){
Example MyTester = new Example();
MyTester.setTestNumber(4);
System.out.println(MyTester.getTestNumber());
}
}
There are two separate instances of Example
created by your application. One is created by main
, and the other by TheTestExample
What you seem to be asking is how main
can get the reference to the Example
instance in the MyTester
variable in your version of the TheTestExample
method.
The answer is that it can't. You cannot access a local variable outside of its scope. The method needs to return the reference in that variable, and the caller needs to save it or use it directly. For example.
tester = tester.theTestExample();
System.out.println(tester.getTestNumber());
public Example theTestExample(){
Example myTester = new Example();
MyTester.setTestNumber(4);
System.out.println(MyTester.getTestNumber());
return myTester;
}
By the way:
MyTester
is not a private variable. It is a local variable. Local variables don't / cannot have an access modifier. Calling them "private" is technically incorrect, and confusing. (For others, and probably for you as well.)
MyTester
and TheTestExample
are egregious violations of Java style conventions. Method and variable names should always start with a lower case letter.