File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Inner Classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Inner Classes" Watch "Inner Classes" New topic
Author

Inner Classes

Kiran Shigli
Greenhorn

Joined: Oct 04, 2008
Posts: 7
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
Sheriff

Joined: Sep 28, 2004
Posts: 19070
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Kiran Shigli
Greenhorn

Joined: Oct 04, 2008
Posts: 7
Thanks for the quick reply Henry.

Yes. MyInner is a method-local inner class. Is there any way to accomplish this?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19070
    
  40

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

Joined: Oct 04, 2008
Posts: 7
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inner Classes