I have a class which has another static
inner class:
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 } }
Unlike inner class, a static nested class cannot access the member variables of the outer class. It is because the static nested class doesn't require you to create an instance of the outer class.
If you want your inner class to access outer class instance variables then in the constructor for the inner class, include an argument that is a reference to the outer class instance. The outer class invokes the inner class constructor passing this as that argument.
If the nested class is static, then it's called a static nested class. Static nested classes can access only static members of the outer class. A static nested class is the same as any other top-level class and is nested for only packaging convenience. A static class object can be created with the following statement.
Method Local inner classes can't use a local variable of the outer method until that local variable is not declared as final. For example, the following code generates a compiler error.
You generally use static classes when you don't need access to the instance variables. If you need to access the instance variables make the class non-static.
As you can see from other answers that you will need a non-static inner class to do that.
If you really cannot make your inner class non-static then you can add required getter and setter method in outer class and access them by creating an instance of outer class from inside inner static class:
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()); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With