3

I have a class structure roughly like this:

final public class Util { private Util() { throw new AssertionError(); // there is not supposed to exist an instance } public static DataElem getData() { return new Util().new DataElem(); } public class DataElem { // class definition } } 

The code for correctly generating an instance of the inner class was taken from this thread. But I didn't like that every time an inner class instance gets made, an instance from the outer one gets made first. And since I put the AssertionError into its constructor, it doesn't work.

Do I have to carry a dummy-instance around just to create instances from the inner class? Can't I make something like Util.DataElem work?

1
  • 1
    Add static to the class header for DataElem? Commented Jul 9, 2014 at 18:32

1 Answer 1

3

You can make your inner class static

final public class Util { private Util() { throw new AssertionError(); // there is not supposed to exist an instance } public static DataElem getData() { return new Util.DataElem(); } private static class DataElem { private DataElem(){} // keep private if you just want elements to be created via Factory method // class definition } } 

and then initialize it like

new Util.DataElem(); 
Sign up to request clarification or add additional context in comments.

9 Comments

what about this return new DateElem()
@Braj yes what about it ?
You should remove the = in return = new Util().new DataElem();.
Simply return new DateElem() there is no need to add the Util class name because it's already inside the Util class.
@JigarJoshi ... no it wasn't. The = is still an error.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.