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?

Community
  • 1
  • 1
Arne
  • 17,706
  • 5
  • 83
  • 99

1 Answers1

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();
jmj
  • 237,923
  • 42
  • 401
  • 438