(Please disregard the previous message; I accidentally sent it before it was
completed.)
I have source code similar to the following.
public class Vehicle
{
protected string dataV;
// ... more protected fields
}
public class FourWheelVehicle : Vehicle
{
protected string dataFWV;
// ... more protected fields
}
public class SuvVehicle : FourWheelVehicle
{
protected string dataSUV;
// ... more protected fields
}
Here's my problem. The number of fields in each class is large; some are
value types and some are reference types. When I write constructors for
FourWheelVehicle and SuvVehicle, I'll be writing a lot of tedious copying,
for instance, something like:
// default constructor
public FourWheelVehicle()
{
this.dataV = "defaultV";
// initialization of other base class protected fields
this.dataFWV = "defaultFWV";
// initialization of other derived class protected fields
}
It seems like it'd be a lot easier to write something like this:
// copy constructor for "base"-sliced part of derived class
public FourWheelVehicle(Vehicle v)
{
base = v.Clone(); // oops! illegal
this.dataFWV = "defaultFWV";
// initialization of other derived class protected fields
}
Even if I could do that, I'm not sure what to do about the further derived
classes, like SuvVehicle and further derived classes. Perhaps something
like:
public SuvVehicle(FourWheelVehicle fwv)
{
base = v.Clone(); // (still illegal)
this.dataSUV = "defaultSUV";
// initialization of other derived class protected fields
}
Might it be ultimately easier to aggregate all the fields into an instance
of a protected object in the class (e.g. VehicleData), or is this overkill?
This would let me do something like:
public FourWheelVehicle(Vehicle v)
{
this.VehicleData = v.VehicleData.Clone();
this.FourWheelVehicleData = new FourWheelVehicleData();
}
This isolates the initialization code to the Clone() method and the
constructor of the data-encapsulation class, rather than scattering it over
all the constructors. But the creation of an additional class solely to hold
data seems like it's just adding unnecessary complication/abstraction.
It seems like there should be a simple solution to this, but that's probably
because I haven't thought about it enough yet. I'd appreciate any input that
a more experienced developer could give. Thanks!
Sincerely,
JJ Feminella
Computer Science/Economics Undergraduate
University of Virginia | School of Engineering and Applied Science