Nested class in a for loop, will there be n instances of the class?

I was wondering how a nested class works in a for loop:

  • will the class object be destroyed after each for intervention?
  • will a class instance be automatically destroyed by garbage?
  • After the for loop completes, is the object from the nested class stored in memory? can it be called from other places in the program?

This is the code:

class Outer { int outer_x = 100; void test() { for(int i=0; i<10; i++) { class Inner { void display() { System.out.println("display: outer_x = " + outer_x); } } Inner inner = new Inner(); inner.display(); } } } class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } } 
+6
source share
3 answers

Having a class definition inside a method is just syntax: it is still a perfectly normal class definition.

For the Inner objects ( new Inner() ) that you create, this means:

  • each object will have the right to garbage collection, like any other object, immediately after the loop iteration
  • yes, the object will eventually be garbage collected
  • the object will be delayed until garbage is collected, but it will not be accessible from other places (since the link to it did not leak).

For the class itself, this means:

  • the class will be loaded as usual (only once)
  • the class will not be reloaded at each iteration
  • the class will not be reloaded on the second test call
  • the class can be GCed according to the usual rules of the GCing classes (which are pretty tight)
+9
source
  • No. The object will hang on the heap until the GC starts up.
  • Yes, when the GC starts up.
  • This will not continue. No, he can not.

If, for example, you passed in the external instance of the ( this ) class to the inner class via the constructor and assigned an Inner class field, in this case the Inner class object will remain in memory for how long since the outer class instance is used somewhere.

0
source

The GC is completely dependent on the JVM, It will run if the internal memory is low, and the GC will get a chance.

-1
source

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


All Articles