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;
e.getNumber() is the common approach. So get or set + VariableName.
You could also have a look HERE.
I would say it depends on the situation. If the field is something simple such as an int and unlikely to change in the future, I would access it using number and not getNumber().
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 use getNumber(), otherwise I use number for clarity and brevity.
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