Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access an outer class's field from a static inner class?

Tags:

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     } } 
like image 933
Karn_way Avatar asked Jul 17 '13 13:07

Karn_way


People also ask

Can static inner class access outer class variables?

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.

How do you access the outer class variable in an inner 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.

Which members of the outer class can we access from a static inner class?

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.

Can inner class access outer class method?

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.


2 Answers

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.

like image 193
Jeff Storey Avatar answered Sep 27 '22 22:09

Jeff Storey


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());         }     } }  
like image 31
anubhava Avatar answered Sep 27 '22 23:09

anubhava