Sam Laporda
Sam Laporda

Reputation: 33

is this a java compiler bug?

Compiler gives a compilation error that does not make sense. "Cannot make a static reference to the non-static field x" I do not make a static reference. A static inner class should have access to the private members of the enclosing class. In fact it does allow me to access super.x

I tried this with java 1.8

class Bug
{
   private int x = 0;
   int y;

   static class BugDerived extends Bug
   {
      BugDerived()
      {
         super();

         super.y = 1; // no error
         y = 1;       // no error
         super.x = 1; // no error !
         x = 1;  // ERROR
      }
   }
}

Upvotes: 2

Views: 191

Answers (2)

Ali Ben Zarrouk
Ali Ben Zarrouk

Reputation: 2020

No, a static method can only reference static fields or other methods. By calling super().x you reference a non-static property from a non-static context, which is allowed.

The following quote is taken from Oracle website.

Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

The inner static class do not have access to members (private methods/variables) of the enclosing class.

Also look here:

a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference. They are accessed using the enclosing class name.

Upvotes: 1

jwenting
jwenting

Reputation: 5663

A static inner class is linked to the outer class at class level, not instance level.

As a result, it can only access static members of the outer class, working in that respect identical to static methods.

Hence, this is not a compiler bug, it's expected behaviour.

When you use super.x, you're accessing the x data member from the instance of the superclass that underlies the instance of the nested class for which the constructor is being run, thus it does have access.

Upvotes: 0

Related Questions