Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java language convention; getters/setters

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;

like image 709
Skogen Avatar asked Sep 17 '26 01:09

Skogen


2 Answers

e.getNumber() is the common approach. So get or set + VariableName.

You could also have a look HERE.

like image 100
thelost Avatar answered Sep 18 '26 14:09

thelost


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.

like image 33
aioobe Avatar answered Sep 18 '26 13:09

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!