How can I return the object of a private inner class
public class MainClass{
public InnerClass getObj(){
return this.new InnerClass()
}
private class InnerClass{
InnerClass(){
}
}
}
-------------
MainClass mc = new MainClass();
mc.getObj(); // assume I am not holding it anywhere.
The above code is giving a null pointer exception, when I checked with the try-catch
blocks.
Also, when tried in debug mode, its says 'ClassNotFoundException
'
But I can see the class file generated as MainClass$InnerClass.class
getObj()
is set to void
so you won't be able to return anything. What should the correct return type be - Pradeep Gollakota 2012-04-05 23:55
Hmmm, I'm not having that same problem. Here's my modified version of your code:
class MainClass {
public static void main( String[] args ) {
MainClass mc = new MainClass();
InnerClass ic = mc.getObj();
System.out.println( ic );
}
public InnerClass getObj() {
return this.new InnerClass();
}
private class InnerClass {
InnerClass() {}
}
}
The result of this code is:
MainClass$InnerClass@64c3c749
main
can see the private
type since it is in the same class. If main
were in a different class it would not wor - Baruch 2014-06-17 11:52
As others have already pointed out all you need to do is fix the return type of your method.
However, you should be aware that you'll get a warning since you're exporting a non-public type in a public method.
Since your getObj()
is public, you should either keep the inner class private and return an Object
, or make it public and return an InnerClass
, depending on your needs.
The following code returns an object in example:
public class MainClass {
private class InnerClass {
InnerClass() { System.out.println("InnerClass"); }
}
public Object getObj(){
return new InnerClass();
}
public static void main (String[] argc) {
MainClass a = new MainClass();
System.out.println(a.getObj());
}
}
It prints out:
bash-4.2$ java MainClass
InnerClass
MainClass$InnerClass@53c059f6
As you can see there are no problems with the constructor.
You simply forgot the return type of your getObj method.
public InnerClass getObj(){return new InnerClass();}