tags:

views:

87

answers:

3

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 Foo's parameter? I don't want to remove Foo's parameter, because it's abstract methods have the generic parameter in their signatures.

A: 

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.

newacct
Won't work as Foo is abstract and can't be instantiated
jitter
Thanks! This is what I thought.
The weird thing is that this answer is right, up until the code snippet which is doing something completely different, and wrong.
Laurence Gonsalves
+3  A: 

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.

jitter
Thanks. This is a clever trick. I think I was just being lazy with my inner classes.
A: 

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.

seh