从外部类访问内部类的私有实例变量 [英] Accessing private instance variable of inner class from outer class
问题描述
为什么此代码不起作用
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);
}
}
这段代码在起作用吗?
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);
}
}
在第一个代码中,当我尝试通过内部类'a'的对象引用内部类'A'的实例变量'x'时,我收到一条错误消息,说我在静态使用内部类语境. 使用其他方法进行相同操作时没有错误.
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. 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.
或者,只需将A
类设置为static
,这意味着它没有封闭的实例.
Alternatively, just make the A
class static
, which means it does not have an enclosing instance.
这篇关于从外部类访问内部类的私有实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!