Possible Duplicate:
Why use getters and setters?
Is there any advantage to making methods to access private variables in your class instead of making the variable public?
For example is the second case better than the first?
//Case 1
public class Shoe{
public int size;
}
//Case 2
public class Shoe{
private int size;
public int getSize(){
return size;
}
public void setSize(int sz){
size = sz;
}
}
What I have seen someday on SO, as answer (written by @ChssPly76) why to use getters and setters
there are much more advantages:
before:
after:
EDIT: one additional new advange when you are using Eclipse – you can create watchpoint on field, but if you have setter you need just a breakpoint, and… breakpoints (e.g. in setter method) can be conditional, watchpoints (on field) cannot. So if you want to stop your debugger only if
x=10you can do it only with breakpoint inside setter.