I tried to implement a factory template with Enum as an internal Enum, but that didn't work. Is there any solution without splitting the internal Enum into a new file? In other words, is it possible to use the factory template of the internal Enum template?
The code is below.
public class SampleParent {
private class InnerChild { }
private class InnerChildA extends InnerChild { }
private class InnerChildB extends InnerChild { }
private class InnerChildC extends InnerChild { }
enum InnerChildEnum {
CHILD_A {
@Override
public InnerChild getInstance() {
return new InnerChildA();
}
},
CHILD_B {
@Override
public InnerChild getInstance() {
return new SampleParent.InnerChildB();
}
},
CHILD_C {
@Override
public InnerChild getInstance() {
return SampleParent.new InnerChildC();
}
},
;
public abstract InnerChild getInstance();
}
private static class InnerChildFactoryEnumStyled {
public static InnerChild getInnerChild(InnerChildEnum child) {
return child.getInstance();
}
}
public static void main(String[] args) {
InnerChild child = InnerChildFactoryEnumStyled.getInnerChild(InnerChildEnum.CHILD_A);
}
}
Compilation error message below
$ javac SampleParent.java
SampleParent.java:12: error: non-static variable this cannot be referenced from a static context
return new InnerChildA();
^
SampleParent.java:18: error: non-static variable this cannot be referenced from a static context
return new SampleParent.InnerChildB();
^
SampleParent.java:24: error: cannot find symbol
return SampleParent.new InnerChildC();
^
symbol: variable SampleParent
3 errors
source
share