Should the inner class be static in Java?

I created a non-static inner class as follows:

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

I named it in the main method as follows:

 Sample obj = new Sample(); obj.sam(); 

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

+4
source share
4 answers

For a non-static inner class, the compiler automatically adds a hidden reference to an instance of the owner object. When you try to create it from a static method (say, the main method), there is no instance owner. This is similar to trying to call an instance method from a static method - the compiler will not allow it, because in fact you do not have an instance to call.

Thus, the inner class must be either static (in this case no instance is required) or you create an instance of the inner class from a non-static context.

+9
source

A non-static inner class has an outer class as an instance variable, which means that it can only be created 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 } } 
+4
source

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

 public class A { public static void main(String[] args) { new A(). new B().a(); } class B { public void a() { System.err.println("AAA"); } } } 
+2
source

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

+1
source

Source: https://habr.com/ru/post/1310376/


All Articles