Arne
Arne

Reputation: 20157

Accessing inner class from static outer util function

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?

Upvotes: 3

Views: 141

Answers (1)

Jigar Joshi
Jigar Joshi

Reputation: 240900

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();

Upvotes: 3

Related Questions