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 楼答案
是的,同一个物体
它不是复制的,只是传递了引用
不是整个对象,只是对象引用作为值传递