Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing inner class from static outer util function

Tags:

java

static

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?

like image 748
Arne Avatar asked Feb 12 '26 05:02

Arne


1 Answers

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();
like image 128
jmj Avatar answered Feb 14 '26 19:02

jmj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!