0

Okay, here's the setup:

EnclosingClass {

    public interface ClassFactory {
        public static SomeClass getInstance(int which);
    }

    private static ClassFactoryImpl {
        @Override
        public static SomeClass getInstance(int which) {
            switch(which) {
            case 1:
                return new SomeClassSubclassA();
            case 2:
                return new SomeClassSubclassB();
            ...
            }
        }
    }
}

I would like to be able to issue statements along the line of:

SomeClass x = EnclosingClass.ClassFactory.getInstance(instanceClassRequest);

Is this possible? If not, how can I access a static nested class through only the interface it implements?

dcow
  • 7,765
  • 3
  • 45
  • 65
  • ...`ClassFactory` is an interface, not a class, and `getInstance` isn't a static method. So you couldn't write a statement like `EnclosingClass.ClassFactory.getInstance` the way you've done it... – Louis Wasserman Jul 06 '12 at 20:24
  • @LouisWasserman changed it. They were supposed to be `static`. – dcow Jul 06 '12 at 20:25
  • @LouisWasserman but yes, the question is how can I access a nested class through its interface.. – dcow Jul 06 '12 at 20:26

1 Answers1

2

The short answer is "no." You'll need to make an instance of your implementation class and put it in a static variable. It'll look like this:

public class EnclosingClass {
    public interface ClassFactory {
        public SomeClass getInstance(int which);
    }
    public static final ClassFactory CLASS_FACTORY;

    private static class ClassFactoryImpl implements ClassFactory {
        public SomeClass getInstance(int which) { /* ... */ }
    }

    static {
        CLASS_FACTORY = new ClassFactoryImpl();
    }
}

Also note that the method on the instance is no longer static.

Then code that invokes it would look like this:

SomeClass x = EnclosingClass.CLASS_FACTORY.getInstance(2);
csd
  • 1,724
  • 10
  • 18
  • Thanks, that's what I was thinking too. However, I was caught up on the `new ClassFactoryImpl();` part. Is it appropriate to construct a new instance of a static class -- in other words, is that normal, valid, and okay? – dcow Jul 06 '12 at 20:29
  • 1
    Yes, it's appropriate. The "static" modifier on that private inner class is a little misleading. All it means in this case is that each `ClassFactoryImpl` instance is not attached to a particular instance of `EnclosingClass`. It's not like the `static` keyword in C or C++. If ClassFactoryImpl were in a separate ".java" file of its own, it would not have the "static" in its class declaration. – csd Jul 06 '12 at 20:31
  • Interesting! I wasn't sure of the finer details about the difference between static nested classes and inner classes so I found this [question on the difference between static nested classes and inner classes](http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class), which is also helpful. – dcow Jul 06 '12 at 20:42