开发者

Access privileges of private members [duplicate]

This question already has answers here: Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜