Is it possible to call an abstract constructor in one method, then pass that to some other methods, which would each cast the new object into specific subclasses? That is,
public AbstractClass createNewAbstractClass() {
//do lots of checks that are the same for each sub class,
//including geting and checking each variable,
//and an exception thrown by the constructor.
AbstractClass abstractClassObject = new AbstractClass(var1, ...);
return abstractClassObject;
}
public SubClassOne createSubClassOneObject() {
SubClassOne subClassOneObject = (SubClassOne)createNewAbstractClass(var1,..);
return subClassOneObject;
}
public SubClassTwo createSubClassTwoObject() { ...
One way to get round this would be to get and check all the variables in one method, then return them in an array, so that the method createSubClassNObject() could use them in the right constructor, but that seems quite messy, and it would mean that each create method would have to check for the same exception in the same way and do the same thing about it, which sounds like exactly the situation you should try to outsource to another method!
I’m interested from a practical point of view – I want my code to be neat and readable – but also from a theoretical point of view – is this actually possible? So even if the answer is no, can you explain why?
There are a couple problems with this:
(SubClassOne)cast would fail because we would really have an instance of typeAbstractClass, not an instance of typeSubClassOnebeing typed asAbstractClass.So unfortunately, the method which returns a
SubClassOnewill need to call aSubClassOneconstructor, which might take the same parameters asAbstractClassand just delegate with asupercall.I don’t think there’s any easy way around duplicating some exception-handling code in each your factory methods; constructors don’t play well with polymorphism. You could have a central constructor which returns
AbstractClass, but it would need a parameter (an enum, aClass, whatever) to tell it which subclass constructor to call.If you don’t want a big swtich statement, you could instead accept a
Classobject and callnewInstance, although this would be slower.