So is there an easy way to make it so a variable will change when another one changes? Essentially:
int a = 0;
int b = a + 5;
int a = 1;
Is there a way to change b because a changed?
Thanks!
So is there an easy way to make it so a variable will change when another one changes? Essentially:
int a = 0;
int b = a + 5;
int a = 1;
Is there a way to change b because a changed?
Thanks!
The easy answer is no, at least not with primitive variables like int. To do something like that, you would have to build a structure with reference variables.
You can use aspect oriented programming (AspectJ) to catch assignments to b
, and have it add code to update a
.
I will not give an example for this, as I do not think it is the right solution except for hard-core experts. Using AOP mean that the code you and others see when reading the source, is different from the code actually executed by the JVM.
Instead consider storing the two variables in a holder class and use setA(..)
and setB(...)
to update the values. The class then knows how to update a when b is being changed.
You could write a small class to help you with this task:
public class Change {
private int a = 0;
private int b = 0;
public Change(int a, int b) {
this.a = a;
this.b = b;
}
public void setA(int newA) {
this.a = newA;
// Change b however you'd like, for example subtract newA.
this.b = this.b - newA;
}
public int getA() {
return a;
}
public void setB(int newB) {
this.b = newB;
}
public int getB() {
return b;
}
public static void main(String[] args) {
// Create a new Change object:
Change chg = new Change(0, 5);
// Upon setting the value of a, you can do something to b in the method.
chg.setA(1);
System.out.println(chg.getB());
}
}
You could try wrapping the calculation within a method and replace all occurrences of b
with the method.
Eg:
// https://www.codechef.com/ide
public static void main(String[] args) {
int a = 0;
printDetails(a);
a=1;
printDetails(a);
}
private static int calcB(int a) {
return a + 5;
}
private static void printDetails(int a) {
System.out.println("a :"+a +". b :" +calcB(a) );
}
Output :
a :0. b :5
a :1. b :6
As others have pointed out, updating the value of one variable based on an assignment to another variable is not possible in Java.
However, you can easily achieve the same effect by providing a method for reading the value. This way, you don't even need a separate variable for b
when you can calculate it on-demand:
private int a;
//...
public int calculateB() {
return a + 5;
}