I'm not sure when exactly i should use set and get methods .My confusion comes from this example that I'm reading right now. we should make a program that make a few balls and throw them and prints the number of throwing.
this program contains of two public class "colors" and "Ball". the colors class determine the color of the ball and Ball class determine the size of the ball.
its colors class:
public class Colors
{
private byte red;
private byte green;
private byte blue;
private byte alpha;
public Colors(byte red, byte green, byte blue, byte alpha)
{
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
}
public Colors(byte red, byte green, byte blue)
{
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = 255;
}
public byte GetRed()
{
return red;
}
public void SetRed(byte red)
{
this.red = red;
}
public byte GetGreen()
{
return green;
}
public void SetGreen(byte green)
{
this.green = green;
}
public byte GetBlue()
{
return red;
}
public void SetBlue(byte blue)
{
this.blue = blue;
}
public byte GetAlpha()
{
return alpha;
}
public void SetAlpha(byte alpha)
{
this.alpha = alpha;
}
public byte Grayscale(byte red ,byte green, byte blue)
{
return (byte)((red + blue + green) / 3);
}
}
and this is ball class
public class Ball
{
private float radius;
private int timesThrown;
public Ball(Color color, float radius)
{
this.color = color;
this.radius = radius;
this.timesThrown = 0;
}
public void Pop()
{
radius = 0;
}
public void Throw()
{
if (radius > 0)
{
timesThrown++;
}
}
public int GetTimesThrown()
{
return timesThrown;
}
}
my question is that why we should use "set" and "get" method in first example? isn't constructor enough ? and why we didn't use set and get in ball class?for example for radius ?