0

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?

Tepa6auT
  • 31
  • 3
  • 1
    If you want each person have their own car, you should create a `Car` for each person. In the current situation, both persons have the same car (which is the `Car` instance referred to as `car1`). – MC Emperor Nov 19 '22 at 13:58
  • You will have to do an actual literal copy at some point in your code. – Louis Wasserman Nov 19 '22 at 16:20

0 Answers0