6

Consider the below example Why we are restricted to declare static member variable in inner Class when there isn't any restriction on inheriting 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 other class which contains static variable than this works fine. Consider below code:

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 restricting static variable in inner class as it is achievable through inheritance? Am I missing something very basic?

Saurab Parakh
  • 1,054
  • 3
  • 12
  • 19

3 Answers3

2

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 that object's methods and fields.
  1. Because an inner class is associated with an instance, it cannot define any static members itself.

I understand it this way:

If inner class have their own static field,and static field have to initialize before class instantiate;

But a innner class only exist with an instance of outterclass ,so it can not initialize its static member before instantiate,then in Contradiction.

user207421
  • 305,947
  • 44
  • 307
  • 483
wangdq
  • 1,874
  • 17
  • 26
1

Because in order to access the static field, you will need an instance of the Outer class, from which you will have to create an instance of the non-static Inner class.

static fields are not supposed to be bound to instances and therefore you receive a compilation error.

The JLS 8.1.3 specifies:

Inner classes may not declare static initializers or member interfaces, or a compile-time error occurs.

Inner classes may not declare static members, unless they are constant variables, or a compile-time error occurs.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

It is very much possible that the purpose of declaring a static variable opposes the purpose of declaring ANY variable in an inner class. Static variables are meant to be used statically - in any other static methods and classes, while inner classes imply that those classes serve their outer classes ONLY.

I guess the Java creators just wanted it this way.

Hung Vu
  • 360
  • 3
  • 11