can we access a private variable using an object

前端 未结 7 1877
一整个雨季
一整个雨季 2020-12-11 08:07

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 cl

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 08:47

    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??

    Because access modifiers don't pertain to the object, they pertain to the class (or assembly, for the internal modifier).

    Even if you access it from a different object, or a static context, as long as you stay in the same class, accessing a private member will work. It's private to the class, not its instances.

提交回复
热议问题