Inner classes in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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
3 Answers
+ 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