Ive looked online for some tutorials but the tutorials are to shallow or to hard to understand. What i want to know is what do the words individually mean. Where would i use getters and setters, what does return, value, get and set actually mean. im guessing get is getting code from somewhere and set is setting a variable to something. Please can someone help a noob out?
2 Answers
2A property is an encapsulated public variable. In other words, it provides controlled access to data belonging to an object. That means the data can be accessed, but the class might do some behind-the-scenes work whenever that property is accessed.
In terms of implementation, instead of this code:
public class GetterSetterClass{
private int length;
public int GetLength(){ return length; }
public void SetLength(int newLength){ length = newLength; }
}
You would have
public PropertyClass{
private int length;
public int Length{
get{ return length; }
set{ length = value; }
}
}
Now, instead of getterSetterClass.GetLength();, you would do propertyClass.Length;. The outcome is the same.
The actual usefulness of properties is lost on this example. You could, e.g. fire events whenever a property is accessed, or increase a counter or have other side-effects happen, which would be impossible if you provided direct access to the public field.
My personal opinion is that a property should have both a getter and a setter, and I scorn properties that only have one or the other. If you only provide read-access to a variable, make a getter. Not only is it annoying to get a compile-time error about read-only properties, it’s also a lot clearer to anyone using your code that there is no way to set that variable.
A good example: Unity’s Time.timeScale provides both read and write access, but then Time.time is a read-only property, … confusing.
The whole thing is called a property. A property is just syntactical sugar for a pair of methods which can be used like a variable.
An example:
private int m_Ammo = 0;
public int Ammo
{
get
{
return m_Ammo;
}
set
{
m_Ammo = value;
}
}
this property actually is this:
private int m_Ammo = 0;
public int get_Ammo()
{
return m_Ammo;
}
public void set_Ammo(int value)
{
m_Ammo = value;
}
internally it really just looks like that. However a property can be used like a variable:
Instead of
int a = XXX.get_Ammo();
// and
XXX.setAmmo(42);
you can do this:
int a = XXX.Ammo;
// and
XXX.Ammo = 42;
It’s actually the same, it’s just a special syntax. The compiler creates the two methods hidden from you.
The nice thing is you can do things like:
XXX.Ammo++;
// or
XXX.Ammo += 20;
This actually does this:
XXX.set_Ammo( XXX.get_Ammo() + 1);
// or
XXX.set_Ammo( XXX.get_Ammo() + 20);