s nitin s nitin - 1 month ago 9
Java Question

Why I cannot declare objects for inner classes in the way mentioned in code?

This code is working properly.However, when i try to change the position of inner class object ,the code isn't working

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);
}
}

//when i create oject for Inner class here code is working
Inner inner = new Inner();
inner.display();
}
}
}

class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}


But when i place Inner class object as in the code below ,code is not working. The IDE was not able to find the inner class while declaring the inner class below its instance

class Outer {
int outer_x = 100;

void test() {
for(int i=0; i<10; i++) {
//now i created object for inner class here
Inner inner = new Inner();
inner.display();

class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
}
}

class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}

Answer

In the second example, you define the Inner class after it is used. It is not available yet when you do new Inner().

Anyway, I would say it is bad practice to create (named) classes within for-loops like this (or even within methods). Anonymous classes are usually fine though. When you need a named class you usually want to define it either in the scope of the class, or in a file by it self.

Comments