Re: Instantiate an abstract class
On Apr 5, 5:48 pm, Joshua Cranmer <Pidgeo...@verizon.invalid> wrote:
On 04/05/2011 05:14 PM, Rob McDonald wrote:
Now, we all know that you can't instantiate an abstract class -- but I
want to anyway... Actually, I would like my abstract class to be abl=
e
to instantiate another instance of whatever concrete class it is at
the time.
Your class is abstract, so you can easily have:
abstract class AFoo {
public abstract AFoo makeInstance();
}
Or, as Patricia mentions:
abstract class AFoo {
public abstract AFoo clone(); // Legal only in Java 5+
}
Each subclass would then implement this method as appropriate.
I can answer your question more directly with reflection, but it's a
method I wouldn't recommend without a very compelling reason why this
approach wouldn't work for you.
Joshua,
That worked great. I don't know why I hadn't come up with that
solution myself.
Most of my online searches had lead down the reflection path and I
quickly got myself wrapped around the axle. I'm going to go with the
above implementation, but I am curious about how it could be made to
work the other way.
Thanks for the help,
Rob