Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing non static variable from within static Inner Class

I need to reference a variable of a top level class from a method within a static class.

This method should act on unique instances of the top level class and so it feels like I shouldn't instantiate the top level class inside the static class.

Basically I want something like

public class TopLevel{
   // private
   int innerV

   public static class Inner implements X {
     for(i=0; i<innerV,i++){
         doSomething 
     }
   }
}

Is it possible to just say this.innerV or something similar in the for loop and similar places?

like image 469
algorithmicCoder Avatar asked Jan 20 '23 16:01

algorithmicCoder


2 Answers

From a static inner class, you can't refer to (nonstatic) members of the outer class directly. If you remove the static qualifier, it will work, because instances of nonstatic inner classes are implicitly tied to an instance of the containing class, so they can refer to its members directly.

Declaring your inner class static removes this link, so you need to either pass an instance of the outer class to the inner class method (or its constructor) as a parameter, or create it inside the method.

like image 121
Péter Török Avatar answered Apr 30 '23 06:04

Péter Török


You can't do that. Create a TopLevel instance and if you make an innerV accessor (getter/setter) or make it public, than you can.

public class TopLevel {
   public int innerV

   public static class Inner implements X {
     for(i=0; i<innerV,i++){
         TopLevel tl = new TopLevel()
         tl.innerV = 12345678;
     }
   }
}
like image 29
lzap Avatar answered Apr 30 '23 07:04

lzap