Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to Increment private variables?

Tags:

java

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.

like image 323
dGFisher Avatar asked Aug 11 '15 03:08

dGFisher


People also ask

How do you increment a variable by 1?

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.

Can we extend private variable in Java?

No. Private variables are only accessible to the class members where it belongs.

Can you modify private variables?

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.


2 Answers

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).

like image 66
Elliott Frisch Avatar answered Sep 19 '22 21:09

Elliott Frisch


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;
}
like image 45
user207421 Avatar answered Sep 20 '22 21:09

user207421