Reputation: 93
I have class C1 and class C2. C1 has a public boolean variable b1.
The value of b1 is set in C1 and then I create a object of Class C2 in C1. ie in C1 I have :
b1 = true;
C2 c2 = new C2();
Now in constructor of C2 , I want to make a decision based on the value of b1. How can I access the value of b1 (which is a variable of Class C1) in the constructor of C2 ? The constructor of C2 cannot have any arguements.
Thanks
Upvotes: 0
Views: 739
Reputation: 4443
There are a couple of ways that you could do this. You could also make b1 static, what @Logard suggested, or C1 could be made into a Singleton:
public enum C1{
INSTANCE;
public boolean b1=false;
}
public class C2{
public C2(){
System.out.println(C1.INSTANCE.b1);
}
}
Upvotes: 0
Reputation: 1513
If the C2 class is defined as an inner class of C1 you can access its outer class like this:
C1.this.b1
Upvotes: 3
Reputation: 7899
In C2 make a object of C1 and then check.
boolean check=new C1().b1
Upvotes: -1