Praveen
Praveen

Reputation: 91175

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.sam();

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?

Upvotes: 6

Views: 11725

Answers (4)

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

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");
    }
  }

}

Upvotes: 2

Ash
Ash

Reputation: 9426

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.

Upvotes: 14

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298898

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
    }

}

Upvotes: 6

Vinze
Vinze

Reputation: 2539

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).

Upvotes: 1

Related Questions