What is the difference between private and protected?

I saw someone explaining and all I got from him is this:

  • protected; Allow a member item to only be accessed from internal or derived source.
  • private; Allow a member item to only be accessed from its owner.

can someone explain in more detail please

preferably in CS code.

thanks in advance

public class ClassA
{
private string text1;
protected string text2;

    public ClassA()
    {
        text1 = "aaa"; // ok
        text2 = "bbb"; // ok
    }
}

public class ClassB : ClassA
{
    public ClassB()
    {
        text1 = "aaa"; // compile error - you can't access text1, because it is visible only in scope of ClassA
        text2 = "bbb"; // ok - text2 is declared as protected in ClassA, so it is accessible in ClassA and all the classes derived from ClassA
    }
}

You can read more on this MSDN page

“private” means that only methods of this class can access the member. “protected” means that methods of this class, or of derived classes, can access the member.

So, a base class can define fields and methods which are not accessible by users of the class, but which are accessible by implementors.

The ownership distinction is rather crude and weak - any instance of the base class can access the private members of any instance of the base class (not only itself), and any instance of the base or any derived class can access the protected members of any other instance of the base or (potentially another) derived class. So it isn’t really very “protected” at all.

public class Shape
{
    private List<Vector2> Points = new List<Vector2>();

    protected void AddPoint(Vector2 point)
    {
       Points.Add(point);
    }

    public float CalculateArea()
    {
        // calculate area based on 'Points' array - it's ok to access it from
        // the class that defines it
        float area = 0;
        int j = Points.Count - 1;
        for (int i = 0; i < Points.Count; ++i)
        {
            area += (Points_.x - Points[j].x) * (Points*.y + Points[j].y) / 2;*_

j = i;
}
return area;
}
}

public class Square : Shape
{
public Square(float width, float height)
{
// we can’t access the private Points list here, but we can access the protected AddPoint method as we’re in a derived class
AddPoint(new Vector2(0, 0));
AddPoint(new Vector2(width, 0));
// etc
}
}

public class SomeComponent : MonoBehaviour
{
public void Start()
{
var shape = new Square(10.0f, 10.0f);
// CalculateArea is public so can be accessed from anywhere
Debug.Log(shape.CalculateArea());
// we can’t access the Points list here, as it’s private, and neither
// can we access AddPoint, as it is is protected and the calling method is
// not in a class derived from Shape
}
}