Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must the inner class be static in Java?

Tags:

java

static

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?

like image 804
Praveen Avatar asked Nov 29 '22 18:11

Praveen


1 Answers

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.

like image 136
Ash Avatar answered Dec 10 '22 23:12

Ash