开发者

Must the inner class be static in Java?

I created a non-static inner class like this:

class Sample {
    public void sam() {
        System.out.println("hi");
    }    
}

I called it in main method like this:

Sample obj = new Sample();
obj.s开发者_JAVA百科am();

It gave a compilation error: non-static cannot be referenced from a static context When I declared the non-static inner class as static, it works. Why is that so?


For a non-static inner class, the compiler automatically adds a hidden reference to the "owner" object instance. When you try to create it from a static method (say, the main method), there is no owning instance. It is like trying to call an instance method from a static method - the compiler won't allow it, because you don't actually have an instance to call.

So the inner class must either itself be static (in which case no owning instance is required), or you only create the inner class instance from within a non-static context.


A non-static inner class has the outer class as an instance variable, which means it can only be instantiated from such an instance of the outer class:

public class Outer{
    public class Inner{
    }

    public void doValidStuff(){
         Inner inner = new Inner();
         // no problem, I created it from the context of *this*
    }

    public static void doInvalidStuff(){
         Inner inner = new Inner();
         // this will fail, as there is no *this* in a static context
    }

}


An inner class needs an instance of the outer class, because there is an implicit constructor generated by compiler. However you can get around it like the following:

public class A {

  public static void main(String[] args) {
    new A(). new B().a();
  }

  class B {
    public void a() {
      System.err.println("AAA");
    }
  }

}


Maybe this will help : http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html the non-static inner class cannot be called in a static context (in your example there is no instance of the outer class).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜