I was wondering if there was an easier way to increment another class's private variables. Here is how I generally would go about it:
If I only need to do this rarely in my code:
pc.setActionsCurrent(pc.getActionsCurrent()-1);
If I need to do lots of incrementing, I would just make a special setter:
//In the PC class
public void spendAction(){
this.actionsCurrent--;
}
//In the incrementing Class
pc.spendAction();
Is there a better way to go about this? If the variable were public
pc.actionsCurrent--;
would be enough, and I can't help but feel I'm over-complicating things.
The increment operator changes a variable by the value of one. Instead of writing varOne = varOne + 1; you can write varOne++; and it will do the same thing.
No. Private variables are only accessible to the class members where it belongs.
The mangling rules are designed mostly to avoid accidents but it is still possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger.
No. The method abstraction is generally the way to go about it, you might also pass in the increment value (and you can leverage that in your implementation). Consider something like
private long increment = 1;
private long myVariable = 0;
public void setMyVariable(long myVariable) {
this.myVariable = myVariable;
}
public void setIncrement(long increment) {
this.increment = increment;
}
public long getMyVariable() {
return this.myVariable;
}
public void addToMyVariable(long val) {
this.myVariable += val;
}
public void incrementMyVariable() {
addToMyVariable(increment);
}
The above would allow the increment value to vary (and this is generally called encapsulation).
Just define an increment method. For generality you could supply the increment as a parameter, and it could be negative:
public void increment(int augend)
{
this.actionsCurrent += augend;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With