Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner Classes

 
Kiran Shigli
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All, Following is the snippet

public class MyOuter2 {
private String a = "Kiran";
void doStuff(){
class MyInner {
public void seeOuter(){
System.out.println(a);
}
}
MyInner in = new MyInner();
in.seeOuter();
}

public static void main(String[] args) {
MyOuter2 inner = new MyOuter2();
inner.doStuff();
}

}

It works fine.
**************************
Also, when I modify the code, something like this compliation fails.

public class MyOuter2 {
private String a = "Kiran";
void doStuff(){
class MyInner {
public void seeOuter(){
System.out.println(a);
}
}
/*MyInner in = new MyInner();
in.seeOuter();*/
}

public static void main(String[] args) {
MyOuter2.MyInner inner = new MyOuter2().new MyInner();
inner.doStuff();
}

}
*******************************************

So, I'd like to know is it possible to instantiate the class MyInner from the main function?

Thanks,
Kiran
 
Henry Wong
author
Marshal
Pie
Posts: 20880
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, I'd like to know is it possible to instantiate the class MyInner from the main function?


In this case, MyInner is a method-local inner class, so no... it can't be instantiated in the main method, because it is not in scope for that method.

Henry
 
Kiran Shigli
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the quick reply Henry.

Yes. MyInner is a method-local inner class. Is there any way to accomplish this?
 
Henry Wong
author
Marshal
Pie
Posts: 20880
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any way to accomplish this?


Accomplish what?

Instantiate an method local inner class in a method where it is not in scope? No.

Move the inner class definition (or make it a regular inner class), and then instantiate it? Sure.

Henry
[ October 04, 2008: Message edited by: Henry Wong ]
 
Kiran Shigli
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok. My intention is to achieve the instantion of MyInner from the main. It is true from your statements that it is not in the scope. Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic