Access privileges of private members [duplicate]
We cannot access a private variable of a class from an object, which is created outside the class, but it is possible to access when the same object is created inside the class, itself. why??
class Program { private int i;
public void method1()
{
Program p = new Program();
p.i = 5; 开发者_StackOverflow社区 // OK when accessed within the class
}
}
class AnotherClass {
void method2()
{
Program p = new Program();
p.i = 5; //error because private variables cannot be accessed with an object which is created out side the class
}
}
see this Access Modifiers
It's a design consideration of OO that allows classes to only expose the functionality that they wish to be re-used by other classes (as public / protected methods) and to keep some functionality internal to the class and not re-usable.
精彩评论