0

On changing non-static inner class to static why there are compile time error on running code says-

Illegal enclosing instance specification

public class TestingInnerStatic{  
   public static void main(String args[]) {
       InnerSame innerSame       = new TestingInnerStatic().new InnerSame();//compile fail
       Outer.InnerDiff innerDiff = new Outer().new InnerDiff();//compile fail
       } 
   public void main() {
       InnerSame innerSame       = new InnerSame();
       Outer.InnerDiff innerDiff = new Outer().new InnerDiff();//compile fail
   }
   static class InnerSame{}

}

class Outer{
    static class InnerDiff{}
}

take a example of other member,this is only a convention and a good practice to call a static member on reference of class but if U call them on object they works not show compile fail.So why there is a compile fail?

5
  • 1
    new Boxing1().new InnerSame(); try changing to new Boxing1.InnerSame(); also the same for the other fails.. Commented May 7, 2015 at 13:16
  • why this is not available on object? Commented May 7, 2015 at 13:18
  • is class Outer in its own file? Commented May 7, 2015 at 13:19
  • 1
    I think new Boxing1().new InnerSame(); shuld be new TestingInnerStatic().new InnerSame(); Commented May 7, 2015 at 13:21
  • @Pratik this is overloaded from only. Commented May 7, 2015 at 13:23

1 Answer 1

1

If an inner class is non-static then you require an instance of the outer class to make an instance of the inner class. But that is not the case for static classes, an instance of an inner static class can exist without an instance of the outer class.

static example:

InnerClass ic = new Outer.InnerClass();

Notice I am not making a new instance of the outer class.

EDIT: reference

Sign up to request clarification or add additional context in comments.

3 Comments

so this is addition access rights available to create a object of inner just only by reference of outer class.why it is not available on object of outer class?
take a example of other member,this is only a convention and a good practice to call a static member on reference of class but if U call them on object they works not show compile fail.So why there is a compile fail?
Don't look at the static inner class as belonging to an instance of the outer class. While you can access static methods and variables from an instance of that class (this is something that IDE's complain about if you do it) it is not the case for static inner classes. From the reference link i provided Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.