Single object class1 associated with many objects from class2

32 Views Asked by At

Is there a way to share an object of class1 (Car) which have fields like "model", "oil volume" to be shared between other objects of class2 (Person). So like the Car object is not like a specific car but more like a general characteristics of a car that each person have. So when doing computation (decrease oil volume) it would be changed in specific person's car and in all the people cars?

class Car {
    int volume;
    String model;
}

class Person {
    String name;
    Car car;

    public void decreaseVolume() {
        this.car.volume--;
    }
}
Car car1 = new Car(100, "Ford100");
Person p1 = new Person(name, car1);
Person p2 = new Person(name, car1);

p2.decreaseVolume();

so that when volume in person2 car is decreased it should not be decreased in person1 car?

1

There are 1 best solutions below

0
On

Sure! The problem here is what linguists call polysemy: a single word, "Car" is used in everyday's language with two different meanings. The solution is to disambiguate the different meanings in the requirement:

  • "Car" can correspond to a category of cars or models (e.g. "a Citroën C4", "a blue BMW Z4"). This "Car" can be found in a catalogue and has some characteristics that are shared by every car of that category. I could not drive this car, as it is only the idea of a car.
  • "Car" can mean a real car, with a serial number, an owner, possibly unique scratches. In principle the real car shares all the characteristics of the category it belongs to. But it may also be modified, with additional options, and perhaps even some tuning that changes ots original characteristics.

The key for you design is then to give different class names to the different meanings, and associate them if they are somehow related:

class CarCategory {
    String brand; 
    String model;
    int maxVolume;
}

class Car {
    CarCategory category; // should be mandatory at construction
    String serialNumber;
    int volume;
    Color color;
    Person owner; 
}

class Person {
    String name;
    ...
}

Here each car has its own volume but all the cars belonging to a category share the same maximum volume.

If you want to allow tuning, it becomes much more complex, and several options are possible for example repeating tunable attributes, clone and change a car category object when tuning, etc.

Note that I have reversed the relationship between the person and the car. In general a car is owned by one person (it could be a "moral person", like a company. But persons may have several cars. If you have a link from person to car like in your original design, a person can have only one car, unless you make it a collection. But then the decrease volume would no longer work as it is. So some fine tuning and experimentation will be required ;-)