Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
125 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...