Meryem Mutluer Meryem Mutluer - 27 days ago 20
Java Question

How do I use non-static OuterClass variable in static NestedClass?

I know static class I use static variable but if I want I use non-static OuterClass variable in static NestedClass. Is there another way out? How can i do this? Or can i do this?

public class NestedClass05 {
int num=1;

public static class Test1{
int num=2;

public int Method1(int a){

return NestedClass05.num+a; // How I can use that
}
}

public class Test2{
int num=3;

public int Method1(int a){
return NestedClass05.this.num+a; // I use like this.
}
}


}

Answer

You need to give the static class the instance of the outer class of which you want to retrieve a variable from. Like:

public class NestedClass05 { int num=1;

public static class Test1{ int num=2;

 public int Method1(NestedClass05 instance, int a){

     return instance.num + a;
  }

}

Comments