What is the point of getters and setters?

Anonymous181 picture Anonymous181 · May 2, 2012 · Viewed 92.6k times · Source

Possible Duplicate:
Why use getters and setters?

I have read books on Java, saying that it is good to create setters and getters for variables such as x and y. For example:

public int getX(){
    return x;
}

public void setX(int x){
    this.x = x;
}

But what is the difference from that and

...(shape.x)...   // basically getX()

and

shape.x = 90;    // basically setX()

If setters and getters are better, could you explain to me what practical problems would arise?

Answer

mprabhat picture mprabhat · May 2, 2012

Multiple reasons:

  • If you allow field access like

    shape.x = 90

then you cannot add any logic in future to validate the data.

say if x cannot be less than 100 you cannot do it, however if you had setters like

public void setShapeValue(int shapeValue){
  if(shapeValue < 100){
    //do something here like throw exception.
  }
}
  • You cannot add something like copy on write logic (see CopyOnWriteArrayList)
  • Another reason is for accessing fields outside your class you will have to mark them public, protected or default, and thus you loose control. When data is very much internal to the class breaking Encapsulation and in general OOPS methodology.

Though for constants like

public final String SOMETHING = "SOMETHING";

you will allow field access as they cannot be changed, for instance variable you will place them with getters, setters.

  • Another scenario is when you want your Class to be immutable, if you allow field access then you are breaking the immutability of your class since values can be changed. But if you carefully design your class with getters and no setters you keep the immutability intact.

Though in such cases you have to be careful in getter method to ensure you don't give out reference of objects(in case your class have object as instances).

We can use the private variables in any package using getters and setters.