I want to make a class with N fields, then subclass it with N-1 fields, and in the subclass the first field should be filled in the constructor. Here's the simplest example:
class Thing {
protected int a;
protected int b;
public Thing(int a, int b) {
this.a = a;
this.b = b;
}
}
class ThreeThing extends Thing {
public ThreeThing(int b) {
this.a = 3;
this.b = b;
}
}
Now, I want to make a method for all Things that respects immutability- it returns a new Thing with 1 added to b.
public Thing transform() {
return new Thing(this.a, this.b + 1);
}
However, when this method is inherited into ThreeThing, the returned object is still a Thing instead of ThreeThing, so I'd have to override the method in ThreeThing. This wouldn't be a big problem, but in my project, there are going to be lots of specialized Things and I don't want to have to override the method in all of them if the behavior is intended to be the same.
Here are the possible solutions I have thought of, none of them satisfy me
- Make a method
cloneforThingandThreeThingthat copies over the fields to a new instance, then use reflection to mutate the private fields to obtain the desired result. The only method that would be needed inThreeThingisclone. - Simply use reflection to instantiate the result of
getClass()with the new values
Is there a way to do this without reflection or a better way to design the objects?