Nested class in for loop, will there be n instances of the class?
Asked Answered
Q

3

6

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

  • will the object of the class be destroyed after every for interation?
  • will the instance of the class be destroyed automatically by "garbage"?
  • once the for loop finishes will the object from the nested class persist in memory? can it be recalled 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();
  }
}
Quoit answered 10/6, 2013 at 9:41 Comment(0)
A
9

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

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

  • each object will be eligible for garbage collection just like any other object, immediately after the loop iteration
  • yes, the object will eventually be garbage collected
  • the object will linger until it is garbage collected, but won't be accessible from other places (since no reference to it leaked).

For the class itself, this means:

  • the class will be loaded as usual (only once)
  • the class will not be re-loaded on each iteration
  • the class will not even be re-loaded on a second invocation of test
  • the class can be GCed according to the normal rules of GCing classes (which are pretty stringent)
Altar answered 10/6, 2013 at 9:45 Comment(2)
I think, object of the class was referring to the Class instance of Inner.Flaviaflavian
@Andreas_D: I realized that he could have meant that and extended my answer.Altar
C
0
  • No. The object will hang out on heap until GC kicks in.
  • Yes, once the GC kicks in.
  • It won't persist. No it cannot.

If you, for example, passed in the outer class instance (this) to the inner class through the constructor and assigned to the field of the Inner class, in that case the Inner class object would remain in memory as long as the outer class instance is used somewhere.

Consentaneous answered 10/6, 2013 at 9:50 Comment(0)
L
-1

GC is totally depends on JVM . It will execute if internal memory is low, and GC get the chance.

Lucy answered 10/6, 2013 at 9:47 Comment(1)
How's this related with question at all? It doesn't address to any of OP's questions.Apopemptic

© 2022 - 2024 — McMap. All rights reserved.