Reputation: 31
Say we have variables int a = 0;
and int c;
.
Is it possible to make it so that c
is always equal to something like a + 1
without having to redundantly retype c = a + 1
over and over again
Thanks!
Upvotes: 0
Views: 162
Reputation: 14217
Firstly, The answer is no, you can't do it directly in Java, but you can redesign your int
class, There is an example:
public class Test {
public static void main(String[] args) throws IOException {
MyInt myInt1 = new MyInt(1);
KeepIncrementOneInt myInt2 = new KeepIncrementOneInt(myInt1);
System.out.println(myInt2.getI());
myInt1.setI(2);
System.out.println(myInt1.getI());
System.out.println(myInt2.getI());
}
}
class MyInt { //your own int class for keep track of the newest value
private int i = 0;
MyInt(int i) {
this.i = i;
}
public int getI() {
return this.i;
}
public void setI(int i) {
this.i = i;
}
}
class KeepIncrementOneInt { //with MyInt Class to get the newest value
private final MyInt myInt;
KeepIncrementOneInt(MyInt myInt) {
this.myInt = myInt;
}
public int getI() {
return this.myInt.getI() + 1; //get the newest value and increment one.
}
}
Int
class, because we need a reference type to keep track of the newest the value a
. like the MutableInt in apache commons.1
class with your own Int
class as a member.getI
method, it's always from the reference Int class
get the newest value a
.Upvotes: 1
Reputation: 2891
Since you have 2 variables tied in a specific way, consider using custom object to wrap a
and c
values. Then you can control the object state inside the class logic. You can do something like this:
public class ValuePair {
private final int a;
private final int c;
public ValuePair(int a) {
this.a = a;
this.c = a + 1;
}
public int getA() {
return a;
}
public int getC() {
return c;
}
}
Upvotes: 1
Reputation: 726479
No, it is not possible to make one variable track another variable. Usually, this is not desirable either: when a value of one variable is tied to the value of another variable, you should store only one of them, and make the other one a computed property:
int getC() { return a+1; }
A less abstract example is a connected pair of age and date of birth. Rather than storing both of them, one should store date of birth alone, and make a getter method for computing the current age dynamically.
Upvotes: 3