Possible Duplicate:
Are Getters and Setters evil?
Why use getters and setters?
I’ve been asking myself this for awhile but why do we actually use Getters and Setter methods? They take up extra space in our code, can someone explain. I’ve posted some code below for a better understanding.
public class Test2
{
public int _ChangeThis = 0;
}
— Other way —
public class Test1
{
public int _ChangeThis = 0;
public setChangeThis(int ChangeThis)
{
_ChangeThis = ChangeThis;
}
}
— Main code —
Test2 testclass = new Test2();
//What is the difference and why do we use the setter? I cannot understand the advantage.
testclass.setChangeThis(1);
testclass._ChangeThis = 1;
Getters and Setters are abstraction wrappers around your object implementations. You may have a property of an object that is actually (as an example) computed based on the value of other field members, but not stored or persisted within the class, thus a getter creates the illusion that the property itself is native to the class, while its implementation is substantially different. Also, getters without setters allow you to create read-only properties and protect internal members of the class from inadvertent and possibly destructive modification.
It’s all about separating the external representation consumed by other applications from the internal implementation plumbing. Those are the basics.