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; // 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
}
}
Now I think every one got my point??
In both the cases above, we are accessing the private variable 'i' through the object 'p'. But inside class it is allowed, outside the class not allowed. Can anybody tell me the reason behind this??
You can access i from within the class because private members can only be accessed by members of the class. In this case it looks strange because p is a different object than the object that accesses the variable, but its still the same class and the restriction is on the class level not on the object level.
class Program
{
private int i;
public void method1()
{
Program p = new Program();
p.i = 5; // OK when accessed within the class
}
}
You can not access i from within another class (unless it is an inner class but that's a different story). Which is completely as expected.
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
}
}
I understand the point you want to make. The restriction on class level looks counter intuitively. And maybe this is wrong. But the member variables are still only accessible from within the class, so you still have total control to guarantee the encapsulation of your privates.
why??
It's true by the language specification. The access modifier private
has the semantics that only the class
or struct
declaring a member is allowed to access that member.
I suggest reading the specification for details. In particular, check out
§3.5.1 Declared Accessibility
§3.5.4 Accessibility constraints
§10.2.3 Access Modifiers
§10.2.6.2 Declared Accessibility
§10.2.6.5 Access to private and protected members of the containing type
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With