I've been struggling with it for a while now. I want to define a finite set of types, some of which would be subtypes to others, where each type is defined by values of its properties. The types would then be used to access their properties and also by a factory method to create instances of them.
It probably doesn't make much sense now so let's say I have this code.
abstract class Car {
final int seats;
final int maxSpeed;
...
}
abstract class DeliveryCar extends Car {
final int maxload;
...
}
Now I want to have types such as FamilyCar
and SportsCar
of supertype Car
and HeavyTruck
of supertype DeliveryCar
with multiple instances of every type and the hard part is the instance variables shouldn't really be "instance" variables - they should have the same values for every FamilyCar
and then some other values for every SportsCar
and still other values for every HeavyTruck
and they should be accessible without an instance. So for example I want to be able to write:
System.out.print("Sports cars' max. speed: " + SportsCar.maxSpeed);
Some of the things that came to my mind but didn't work out:
- static values, but java doesn't allow overriding static members
- enums, but there's no subclassing of enums in java, so every
Car
that's notDeliveryCar
would have to have themaxload
and possibly other members - simulated enums, something like this:
class CarType {
final int seats;
final int maxSpeed;
...
static final CarType FAMILY_CAR = new CarType(5, 180);
static final CarType SPORT_CAR = new CarType(2, 280);
...
CarType(int seats, int maxSpeed) {
...
}
class DeliveryCarType extends CarType {
final int maxload;
...
static final DeliveryCarType HEAVY_TRUCK = new DeliveryCarType(3, 150, 500)
...
DeliveryCarType(int seats, int maxSpeed, int maxLoad) {
...
}
It would do what I need but then it would also be valid do wrtie something like DeliveryCar.SPORTS_CAR
.
I'm not sure if there's some fundamental flaw in the design I'm trying to achieve but it's bugging me so much because I cannot seem to be able to solve something that could be solved with just overridable static members which I think some other languages (e.g. Objective-C) implement.
EDIT: I've also read this discussion (among others) but none of the ideas there seems to solve my problem.