+ 1

Inner classes in java

Why can't we declare static members in the non-static inner class in java?

2nd Aug 2020, 1:55 PM
Gauri Shirkande
Gauri Shirkande - avatar
5 Antworten
+ 8
Because an inner class is an instance of the outer class. https://stackoverflow.com/questions/1953530/why-does-java-prohibit-static-fields-in-inner-classes#:~:text=An%20inner%20class%20is%20a,constant%20fields%20(%C2%A715.28).
2nd Aug 2020, 2:06 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
we can if there is static class Inner or if non-static Inner has static final member class Outer { static class Inner{ static int x = 10; Inner() { System.out.println(x); } } public static void main(String args[]) { new Outer.Inner(); } }
2nd Aug 2020, 2:36 PM
zemiak
+ 3
Thank you everyone!
2nd Aug 2020, 3:13 PM
Gauri Shirkande
Gauri Shirkande - avatar