I have two classes in a package and I want to know how I can pass the state of a boolean from one class to the other. Basically in class 1 the user has an option to either load a file or to start the application without loading a file. If they load a file I need class 2 to check if the boolean in class 1 is true. I'm confused because the way I understand it is that the instance of class 1 is not created until class 2's " clickButton() " method is called. So I thought if I create the instance of the class after clickButton is called, then I would get the updated boolean statement. But it's not working...I'm always getting false. A simplified look of my classes are below:
CLASS 1:
public class Class1 {
public boolean isLoaded = false;
public void loadFile(){
if (fileLoaded == true){
isLoaded = true;
}
}
public boolean checkIfLoaded(){
return isLoaded;
}
CLASS 2:
public class Class2 {
public void clickButton(ActionEvent e){
Class1 instance = new Class1();
system.out.println(instance.checkIfLoaded());
}
}
Is there a good way to communicate a boolean change between two classes after compile time?
Creating a new class will not save the value of the variable. There are several ways to solve this: 1) Pass ClassA to the ClassB constructor
public Class2 (Class1 class1) {}
but I think this is not very convenient.
2) You can also declare checkIfLoaded and isLoaded static and just execute ClassA.checkIfLoaded ();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.