المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : encapsulation understanding problems



C# Programming
01-17-2010, 03:40 PM
hi, im newbie in c# encapsulation,recently i just study an article on the encapsulation for hiding its field in class so that it protect the data by outside world...but im confuse...i did try some example.. .Below is my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EncapsulationExample
{
class Program
{
static void Main(string[] args)
{
School d = new School();
d.SetSchool("Alan");
Console.WriteLine("The School is :" + d.GetSchool());
d.SetSchool("Sing");//changing parameter will also change private //variable name as well

Console.WriteLine("The School is :" + d.GetSchool());

d.testing = "month";
Console.WriteLine("The testing is :" + d.testing);


}
}
public class School
{
private string name;

public string testing;
// Accessor.
public string GetSchool()
{
return name;
}
// Mutator.
public void SetSchool(string a)
{
name=a;
}
}
}

...here is my confusion..even the private variable name has been declared as private, but the variable can also be changed by assigning different parameter in SetSchool method...which is same as public string testing where we can change the variable of testing as well.What is the difference with using method and without method(access variable directly from public variable) ??....What does "protect the data by outside world" actually means? any explanation with coding would be much appreciated..Thanks in advance