有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在构造函数中传递接口对象我是否复制接口对象?

以下代码:

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();
}

我的问题是:在garage对象中调用activateHyperDrive的car与main中调用的car是同一个car实例,还是在传递给garage时复制的?AFAIK Java只是通过值传递的,所以对象不是被复制的吗?会出现什么问题吗?谢谢


共 (1) 个答案

  1. # 1 楼答案

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

    是的,同一个物体

    is it copied when it´s passed to garage?

    它不是复制的,只是传递了引用

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

    不是整个对象,只是对象引用作为值传递