使用一个对象,我们可以访问私有变量我们可以、变量、对象

由网友(天青色等烟雨)分享简介:我们无法从一个对象,它是类之外创建访问类的私有变量,但它是可能的,当同一个对象的类中创建访问,本身。为什么?We cannot access a private variable of a class from an object, which is created outside the class, but it...

我们无法从一个对象,它是类之外创建访问类的私有变量,但它是可能的,当同一个对象的类中创建访问,本身。为什么?

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

在上述两种情况下,我们要访问私有变量'我'通过对象P。但里面的类是允许的,外面的类不允许的。谁能告诉我这个?背后的原因

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

推荐答案

您可以在类的内部访问我,因为私有成员只能由类的成员访问。在这种情况下,看起来很奇怪,因为p是比访问可变对象是不同的对象,但其仍然是相同的类和限制是在类层次上没有对象层级。

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.

阅读全文

相关推荐

最新文章