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?
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:
The key for you design is then to give different class names to the different meanings, and associate them if they are somehow related:
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 ;-)