-1

Suppose I have two objects of PARKING class that are respectively P1 and P2. PARKING class have unique identifier (UUID). I also have an object of class CAR which its name is mycar.

My car is currently built in P1 and now wants to migrate to P2.

Here is some code:

public class PARKING {

    public String ID = new String();
    ID  = UUID.randomUUID().toString();
    CAR car;

    public PARKING(CAR car) {
        this.car = car;
    }
    public PARKING (){

        }
    }


    public class CAR {

        public int ID;
        public String name = new String();

    }

    public static void main(String[] args) {
        CAR mycar = new CAR();
        PARKING P1 = new PARKING(mycar);
        PARKING P2 = new PARKING();   
    }    
}

Note that I don't want that P2 take mycar. I mean something like this P2.setCAR (P1.getCAR());

I want the car itself migrate from its current object which is P1 to another object which is P2.

I hope I have explained the problem clearly. Thanks in advance.

Vampire
  • 35,631
  • 4
  • 76
  • 102
Farhood
  • 3
  • 1
  • 6
  • So you want to create a method that takes the parameters `PARKING p1, PARKING p2` that moves the cars in between? What's the issue you're having with making that method? – Draken Apr 28 '16 at 13:12
  • 1
    Since it's `PARKING` that has a reference to `Car`, it's up to that class to handle the switch (either by the setter/getter combo you you described, or by other means). You can't have a `Car` switch parking lots without involvement of the Parking class. – Kayaman Apr 28 '16 at 13:19

1 Answers1

0

If I've understood your query, it's quite simple what you want to do, here is an example method that can complete that:

public void moveCars(PARKING toMoveFrom, PARKING toMoveTo){
    //Checking a car can be moved from A to B
    if (toMoveFrom.car != null && toMoveTo.car == null){
        //Put car in B
        toMoveTo.car = toMoveFrom.car;
        //Remove car from A
        toMoveFrom.car = null;
    }
    else{
        //Either car blocking way or no car in original parking, handle error
    }
}

This is assuming you have made the PARKING.car property public or added a public getter/setter so you can access it. If however you want the car to be able to move itself, then you need to create a property on the Car class that stores the parking as well and change it via that instead. Choices, but that's up to you

Draken
  • 3,134
  • 13
  • 34
  • 54