Let’s say I have two classes. Both have the same member fields (including the same names), but one class’ member fields are declared as final (immutable), and the other is not. Most of the member methods will work for both classes.
How could I share the member methods of the immutable class with the other class (as if by inheritance or something) without having to copy the entire methods to the other class. I’m figuring there’s no such way but I figured I’d ask first. Otherwise I’ll just declare them in difference namespaces and give them the same class name. It should be noted that not ALL of the immutable class methods will work for the mutable one.
public class ImmutableDoubleLine {
public final DoublePoint origin;
public final DoublePoint endPoint;
// ...
public double getLength() {
return origin.calcDistance(endPoint);
}
}
public class MutableDoubleLine {
public DoublePoint origin;
public DoublePoint endPoint;
// ...
// same code as immutable class
public double getLength() {
return origin.calcDistance(endPoint);
}
}
First off, and this is very important.
Unless the class
DoublePointis internally immutable, and all it’s instance variables down the line are internally immutable, all you have done with thefinal DoublePoint originstatement is make the reference tooriginandendpointwhere they can’t be changed to point to different instances, you have NOT madeImmutableDoubleLineimmutable.I mention this because you don’t show the code for
DoublePoint.Second, to your actual question, use an
Interfaceand have both classes implement it:I would try and make everything immutable as much as possible, it makes debugging easier and makes concurrency much easier as well.