sravanreddy001
sravanreddy001

Reputation: 257

How to return object of private inner class object java

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

Upvotes: 1

Views: 6842

Answers (4)

Riccardo T.
Riccardo T.

Reputation: 8937

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.

Upvotes: 1

Pradeep Gollakota
Pradeep Gollakota

Reputation: 2181

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.

Upvotes: 1

Ryan Nelson
Ryan Nelson

Reputation: 4666

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

Upvotes: 3

user973999
user973999

Reputation:

You simply forgot the return type of your getObj method.

 public InnerClass getObj(){return new InnerClass();}

Upvotes: 0

Related Questions