Java generics/abstract/innerclass syntax question
I've got the following:
public abstract class Foo<T>{
//contents of Foo //
...
public class Bar<Q> extends Foo<T>{
//contents of Foo.Bar //
...
}
}
Later, in another class and java file, I am trying to construct an instance of the inner Bar class above, using the outer abstract class as a supertype. To complicate things even more, the new class has it's own generic. The following does not work:
public class SomeOtherClass<A>{
private Foo<A> x;
public SomeOtherClass(){
x = Foo<A>.Bar<A>();
}
}
But this doesn't work; and neither do all the other combos that I've tried. So how do I go about instantiating x? Can it be done with out removing Fo开发者_Python百科o's parameter? I don't want to remove Foo's parameter, because it's abstract methods have the generic parameter in their signatures.
To get an instance of the inner class you first need an instance of the outer class. As Foo
in your example is abstract you can't instantiate the outerclass. Thus you also can't instantiate the innerclass.
For your example you can use the dirty trick (as there are no abstract methods to implement)
public class SomeOtherClass<A>{
private Foo<A> x;
public SomeOtherClass() {
//create anonymous extension of the abstract outer class
//for a real abstract class this would mean you have to
//implement all methods which are declared abstract
x = new Foo<A>(){};
x = x.new Bar<A>();
}
}
So actually you should ask yourself if your class structure is right, if you need access to a innerclass (Bar
) of an abstract class (Foo
) without really needing the enclosing class.
Aside from inquiry for exploration's sake, what's the motive for nesting Bar
within Foo
? This looks almost like how enum
and Enum
work, but without the behind-the-scenes compiler magic to hide most of the oddities.
If Foo
is incomplete, it's meant to be extended from afar -- even if only from no farther than within its containing package (if the class wasn't declared public). The extensions being nested within the incomplete husk will only confuse potential clients.
If you share more detail about the actual problem domain, you'll likely summon plenty of specific replies as to how to better model the solution.
Bar is a non-static inner class of Foo. That means that you need an instance of Foo to construct an instance of Bar. If you don't want to need an instance of Foo, then Bar should be made a static inner class.
精彩评论