For obvious reasons, we cannot instantiate an abstract class directly like so:
AbstractObj obj = new AbstractObj();
Where AbstractObj is a class of the form:
public abstract class AbstractObj {
//... Body omitted
}
However if we have extending classes, such as the following:
public class ConcreteObj extends AbstractObj {
//... Body omitted
}
public class AnotherObj extends AbstractObj {
//... Body omitted
}
Is it possible to instantiate an object in the following manner? This determines which constructor has to be used based on the class of the variable passed in. Assume for now that o1 and o2 are guaranteed to be of the same type.
protected AbstractObj computeDiff(AbstractObj o1, AbstractObj o2){
AbstractObj delta = ...?
}
For example, in the above, if o1 is of type ConcreteObj, is there a way to recognise at runtime whether or not it is of this type and use the appropriate constructor?
o1.getClass(). Then, if it has a default constructor, you can call it witho1.getClass().newInstance().instanceofto check whethero1is indeed aConcreteObj.