我可以从静态内部类访问外部类的字段吗?
问题内容:
我有一堂课,还有另一个static
内部课:
class A {
private List<String> list;
public static class B {
// I want to update list here without making list as static
// I don't have an object for outer class
}
}
问题答案:
从其他答案中可以看出,您将需要一个非静态内部类来执行此操作。
如果您确实不能使内部类成为非静态类,则可以在外部类中添加所需的getter和setter方法,并通过在内部静态类内部创建外部类的实例来访问它们:
public class A {
private List<String> list = new ArrayList<String>();
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public static class B {
// i want to update list here without making list as static
void updList() {
A a = new A();
a.setList(someOtherList);
System.out.println(a.getList());
}
}
}