Changing a variable permanently in a static method
Let's say I have a public class with static methods, one of them, for example:
public static void test(boolean b){
b = !b;
}
Let's say this is the name of the Test class. From another class where I have a boolean variable a = false, I call
Test.test(a);
How can I make it constantly change and not just change it in the scope of static methods?
source to share
It seems to me that you are looking for Mutable Boolean
, the simplest of which is AtomicBoolean .
private void changeIt(AtomicBoolean b) {
b.set(!b.get());
}
public void test() {
AtomicBoolean b = new AtomicBoolean(false);
changeIt(b);
System.out.println(b);
}
source to share
in the class Test
you can define boolean variable as static
public static boolean a;
and outside of the change or access class with Test.a=false;
ora=Test.a
and if you need to use methods, you can hide the static method with inheritance:
public class HideStatic {
public static void main(String...args){
BaseA base = new ChildB();
base.someMethod();
}
}
class BaseA {
public static void someMethod(){
System.out.println("Parent method");
}
}
class ChildB extends BaseA{
public void someMethod(){
System.out.println("Child method");
}
}
source to share
I think you are asking to call the link . You can get this in Java using arrays:
public static void test(boolean[] b){
b[0] = !b[0];
}
boolean[] param = new boolean[] {a};
test(param);
a=param[0];
//a changed
It works, but it's ugly. If you need to return more than one value, look at the Pair or Tuple structures .
source to share