Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
  }
}
like image 211
Carlo Luther Avatar asked Jun 10 '13 09:06

Carlo Luther


People also ask

Can we create instance of nested class?

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass.

How many times can a class be nested within a class?

A class can be nested up to any depth; there is no practical limit, but a class nested deeper that two is almost always unnecessary.

Are nested classes members of a class?

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

Can a nested class have its own static members?

A nested class can have its own static members. Explanation: The nested classes are associated with the object of the enclosing class. Hence have direct access to the members of that object. Hence the inner class can't have any static members of its own.


1 Answers

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)
like image 113
Joachim Sauer Avatar answered Nov 04 '22 17:11

Joachim Sauer