Whimusical
Whimusical

Reputation: 6649

Factory in inner class, not possible?

Id like to hide instantiaton details of my inner class from my outer class. My inner class needs to be non-static in order to access outer's variables

If I try to write a buildNew() static method it throws an error as it seems it is not possible to have static methods in inner classes.

Do I have to rennounce to the feature and instantiate the inner class in parent's or either pass all parent's variables to the inner in order to qualify for static?

Upvotes: 5

Views: 3758

Answers (1)

Misha
Misha

Reputation: 28163

I think the two options you outlined (make Inner static or put those factory methods in Outer) are fine and you don't gain much by going with the following, but that's a matter of opinion.

You can replicate the function of static methods and variables by having a singleton (with respect to Outer instance) object to hold them. In this case, it would look something like this:

class Outer {

    int foo = 0;
    int bar = 5;

    private final InnerFactory innerFactory = new InnerFactory();

    List<Inner> test() {
        Inner fromFoo = innerFactory.newFromFoo();
        Inner fromBar = innerFactory.newFromBar();

        return Arrays.asList(fromFoo, fromBar);
    }

    private class InnerFactory {

        Inner newFromFoo() {
            // I'm an inner class, so I can access member variables 
            // of enclosing Outer
            return new Inner(foo);   
        }

        Inner newFromBar() {
            return new Inner(bar);
        }
    }

    public class Inner {

        int baz;

        Inner(int baz) {
            this.baz = baz;
        }
    }

}

Upvotes: 2

Related Questions