Public class Example {
private int number;
public Example(int number){
this.number = number;
}
public int getNumber(){
return number;
}
public void setNumber(int number){
this.number = number;
}
public static void main(String[] args){
Example e = new Example(5);
What is preffered when accessing a variable within its own class;
“e.number” or “e.getNumber()” ?
Edit:
I think the most important question is: does the compiler know the method you call is a getter or setter. So, will e.setNumber(5); be as fast as e.number = 5;
I would say it depends on the situation. If the field is something simple such as an
intand unlikely to change in the future, I would access it usingnumberand notgetNumber().If the field represents something more involved that could in some situation perhaps be computed in future situation or possibly overridden in a subclass,
getNumber()is the obvious choice.My rule of thumb: If there is any remote chance that I can benefit from going through
getNumber()I usegetNumber(), otherwise I usenumberfor clarity and brevity.