Question:
how can i create instance of inner class outside its enclosing class?
anonymous
2012-04-23 00:05:43 UTC
class Main
{
int a=10;
void display()
{
System.out.println(a);
Inner in=new Inner();
in.display();
}
class Inner
{
int c=20;
void display()
{
System.out.println("a= "+a);
System.out.println(c);

}
}

}
class Innerclasses
{
public static void main(String ar[])
{
Inner m2=new Inner()); // here i want to create instance of inner class, but java compiler shows error
m2.display();
}
}
Three answers:
Rami
2012-04-23 00:15:00 UTC
new main().new innor();
?
2012-04-23 07:25:01 UTC
there are some obvious syntax error in your code. are those typos?

1. variable a is not defined in class Inner

2. there's an extra closing parenthesis in this line of class Innerclasses: Inner m2=new Inner());



fix those and it should be ok.



by the way, make sure those 2 or 3 classes are inside the same package. i don't know the use of class Main. Innerclasses and Main are almost the same, you should have get it in the first place. you have instantiated class Inner in there, see.
?
2012-04-23 07:30:27 UTC
Inner m2=new Inner()); extra bracket

Is it the problem



No. No.

You can not create inner class objects in outside classes, I think


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...