I was wondering how a nested class works in a for loop:
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();
}
}
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.
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.
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.
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.
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:
For the class itself, this means:
test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With