简体   繁体   English

从外部类访问内部类的私有实例变量

[英]Accessing private instance variable of inner class from outer class

Why isn't this code working 为什么此代码不起作用

public class BB
{
    private class A
    {
        private int x;
    }

    public static void main(String[] args)
    {
        A a = new A();
        a.x = 100;
        System.out.println(a.x);
    }
}

while this code is working? 当这段代码有效时?

public class BB
{
    private class A
    {
        private int x;
    }

    static int y = 3;

    public static void main(String[] args)
    {
        BB b = new BB();
        b.compile();
        System.out.println("y = "+ y);
    }
    public void compile()
    {
        A a = new A();
        a.x = 100;
        System.out.println(a.x);
        System.out.println("y = "+ y);
    }
}

In first code, When I am trying to refer to instance variable 'x' of inner class 'A' by an object of inner class 'a', I am getting an error saying that I'm using inner class in static context. 在第一个代码中,当我试图通过内部类'a'的对象引用内部类'A'的实例变量'x'时,我得到一个错误,提示我在静态上下文中使用内部类。 There is no error while doing the same in some other method. 使用其他方法进行相同操作时没有错误。

Your error has nothing to do with field access. 您的错误与字段访问无关。 Compilation fails for this line: 此行的编译失败:

A a = new A();

Reason: you cannot instantiate an inner class without an enclosing instance, which is exactly what that line of code tries to do. 原因:如果没有封闭的实例,则无法实例化内部类,而这正是该代码行尝试执行的操作。 You could write instead 你可以写

A a = (new BB()).new A();

which would provide an enclosing instance inline. 它将提供一个封闭的实例内联。 Then you will be able to access the private field as well. 然后,您也可以访问私有字段。

Alternatively, just make the A class static , which means it does not have an enclosing instance. 另外,只需将Astatic ,这意味着它没有封闭的实例。

private class A is like an instance member and we can not use instance member inside static method without making its object. 私有类A就像一个实例成员,我们不能在没有其对象的情况下在静态方法中使用实例成员。 So first we need to object of outer class than we can use instance inner class. 因此,首先我们需要对象的外部类,而不是实例内部的类。 And below code is working fine. 下面的代码工作正常。

class BB { private class A { private int x; BB级{私有A级{私有int x; } }

public static void main(String[] args)
{
    BB bb = new BB();
    BB.A a = bb.new A();
    a.x = 100;
    System.out.println(a.x);
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM