Why are we forbidden to declare a static member variable in the inner class in java?

Consider the following example. Why are we forbidden to declare a static member variable in an inner class when there are no restrictions on the inheritance of static variables in inner classes ?

public class Outer { public class Inner { public static String notAllowed; /* Above line give following compilation error The field notAllowed cannot be declared static in a non-static inner type, unless initialized with a constant expression */ } } 

But now, if my inner class extends another class that contains a static variable, than this works fine. Consider the code below:

 public class Outer { public class Inner extends InnerBase { /* Since it extends InnerBase so we can access Outer.Inner.allowed */ public Inner(){ Outer.Inner.allowed = null; // Valid statement } } } public class InnerBase { public static String allowed; } 

So, what is the reason for limiting a static variable in an inner class as achievable through inheritance ? Did I miss something very basic?

+6
source share
2 answers

Since to access the static field you will need an instance of the Outer class from which you will need to create an instance of the non-static Inner class.

static fields should not be associated with instances, and therefore you get a compilation error.

JLS 8.1.3 indicates:

Inner classes cannot declare static initializers or member interfaces or compile-time errors.

Inner classes cannot declare static members unless they are constant variables or a compile-time error.

+1
source

From oracle website:

1) As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to these object methods and fields.

2) Since the inner class is associated with an instance, it cannot define any static members.

As I understand it:

If the inner class has its own static field, and the static field must be initialized before the class instance;

But the inner class only exists with an outterclass instance, so it cannot initialize its static member until the instance is created, and then in Contradiction.

+1
source

All Articles