0

I have two classes, "class1" and "class2". When I initialize a boolean called "test" (true) in "class1" and ask for it's value in an if- statement in "class2" everything works fine. But as soon as I change the value from "test1" to false in a method it doesn't recognize the changes in the if-statement in "class2".

My goal is that the boolean value changes as soon as the rewarded video ends and that the if-statement in class2 recognizes it.

class1:

public boolean test1= true; //This is recognized by the if-statement in class2

    ...

    @Override
    public void onRewardedVideoAdRewarded(Placement placement) {
        test1 = false; //this is getting ignored by the if-statement in class2
    }

class2:

Class1 class1 = new Class1();

if(class1.test1){
    // Do something
}else{
    // Do something else
}

I hope you can help me, thank you.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
HavanaSun
  • 446
  • 3
  • 12
  • 39

2 Answers2

2

if you use a static variable, your problem would be solved. make a Class like this:

public class MyStatics {
public static boolean test1=true;

}

now change class 1 to:

 @Override
public void onRewardedVideoAdRewarded(Placement placement) {
    test1 = false; 
}

and keep class 2 as what it is.

note:

static variable can be accessed everywhere and you dont need to define them again.

what was your problem?

class2 ignored class1, because when you used "new" class1, in simple words, it's like all your setup reverted to default , and your default was public boolean test1= true;

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
0

Java is a so-called object oriented language. For all 'static' members defined in a class named, say, 'Movie', there is one of them regardless of how many movie objects are created. But for normal (non-static) members, there's one per created object.

So, when you write Class1 class1 = new Class1(); you are making a new class1 object, and thus, a copy of every non-static member inside. That means there are at least 2 instances of a class1 object in your runtime, and when you say test1 = false, you are updating the test1 field that is part of a different object vs. the one being read by the other class.

The solution? Pass an instance of class1 to some method (or the constructor) of class2, or possibly use a static field or possibly some other solution; you did not paste enough code to make a meaningful guess as to what the best approach is here.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72