I have a class (let's say Vehicle) with a rather large number of subclasses (Car, Bike, ..). Every subclass stores specific information on the type of the subclass (# of tires, ..).
I want to ensure that all this information is already enforced (at compile-time). So I don't want to specify this data in the constructor of the subclass (because I might forget to set some of them). I could put this info in the constructor of Vehicle, but this would clutter code quite a lot, since I have many of those parameters.
public class Vehicle {
int numberOfTires;
public Vehicle(int numberOfTires, ...) {
...
}
}
public class Bike {
public Bike() {
super(2,...);
...
}
}
I end up with completely unreadable constructors. It would also store this info per instance, even though it is specific to the subclass.
An alternative way is to introduce abstract static getters/setters and store the info in the subclasses.
public class Vehicle {
...
abstract public int getNumberOfTires();
}
public class Bike {
static int numberofTires = 2;
...
public int getNumberOfTires() {
return numberOfTires;
}
}
This seems way cleaner and also stores the info per subclass and not per instance but there will be a lot of code duplication in the subclasses. Right now, all the subclasses contain ~20 setters/getters but virtually no real functionality. Is there a clean way of avoiding this? Perhaps using the Factory method or alike?