1

Following code:

public interface VehicleAbilities {
   public void activateHyperDrive();
}

public class Car implements VehicleAbilities {

   public void activateHyperDrive() {
       fastenSeatBelt();
       pressTheRedButton();
   }
}

public class Garage {
   VehicleAbilities iVehicle;
   public Garage(VehicleAbilities aVehicle) {
       iVehicle = aVehicle;
   }

   public void fireUpCars() {
       iVehicle.activateHyperDrive();
   }
}

public static void main (String[] args) {
    Car car = new Car();
    Garage garage = new Garage(car);
    garage.fireUpCars();
}

My question is this: Is the car that activateHyperDrive is called on in garage object the same car instance as in main, or is it copied when it´s passed to garage? AFAIK Java is pass-by-value only, so isn´t the object copied? Are there any problems that can come up? Thank you.

最白目
  • 3,505
  • 6
  • 59
  • 114

1 Answers1

2

Is the car that activateHyperDrive is called on in garage object the same car instance as in main

Yes, the same object.

is it copied when it´s passed to garage?

It is not copied, just the reference been passed.

AFAIK Java is pass-by-value only, so isn´t the object copied?

Not the whole object, just object reference been passed as a value.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307