This probably has a very simple solution, but I can't seem to figure it out...
We have a bunch of classes of the form xQuantity, e.g. DistanceQuantity, AreaQuantity, etc., which extend a class DimensionQuantity. Now you can add or subtract DistanceQuantity's or AreaQuantity's, etc., but you can't mix them. All of the subclasses have methods like add(), subtract(), ge(), etc., so it would be nice to put the shared logic into DimensionQuantity, but I keep running into cast problems.
So far the best I have come up with is to generate an object, and then cast it in the subclass's method, but it would be nice to get rid of the subclass add() (and the other similar methods) altogether! Here is the code (with some stuff left out):
In DistanceQuantity:
public DistanceQuantity add(DistanceQuantity d1) {
Object o = new DistanceQuantity(scalar + d1.scalar, REF_UNIT);
return (DistanceQuantity) o;
}
In DimensionQuantity:
@SuppressWarnings({"rawtypes", "unchecked"})
public Object add(DimensionQuantity d1) {
Class c1 = this.getClass();
Class c2 = d1.getClass();
if (c1 != c2)
throw new RuntimeException();
double d = scalar + d1.scalar;
Constructor c = null;
c = c1.getConstructor(Double.TYPE, AbstractUnit.class);
Object o = null;
o = c.newInstance(d, REF_UNIT);
return o;
}
Can someone (or someones) suggest a better way?!