说你有
public class Car{
private Engine m_eng;
public Car(){
}
public Engine getEngine(){
return m_eng;
}
public void setEngine(Engine engine){
m_eng = engine;
}
}
public class Engine{
private String m_name;
public Engine(){};
public Engine(String name){ m_name = name;}
public String getName(){
return m_name;
}
public void setName(String name){
m_name = name;
}
}
public static void main(String[] args){
Engine eng1 = new Engine("abc");
Car car1 = new Car();
car1.setEngine(eng1);
Car car2 = new Car();
car2.setEngine(car1.getEngine());
}
问题:car1和car2的引擎是引用相同的Engine实例,还是当我car2.setEngine(car1.getEngine())
时,它会自动生成car1.getEnginer()的深层副本并设置为car2?
答案 0 :(得分:6)
CAR1 ---------------> ENG1
car2.setEngine(car1.getEngine());
结果
car1 ---------------> eng1< ------------------ car2
从而指向相同的引擎实例
答案 1 :(得分:4)
是的,确定这些是同一个实例。
答案 2 :(得分:3)
没有深层复制品。两个Car
实例都引用Engine
的同一个实例。
答案 3 :(得分:3)
正如其他人所说,当你这样做时
car2.setEngine(car1.getEngine())
engine
中的car2
与car1
中的对象引用相同。使用==
:
System.out.println(car2.getEngine() == car1.getEngine()); //prints "true"
当我执行
car2.setEngine(car1.getEngine())
时,它会自动制作car1.getEngine()
的深层副本,并设置为car2
?
这里要小心,因为在执行该声明时没有对象引用的副本,它不是深拷贝也不是浅拷贝,它是相同的对象参考。这意味着,如果您修改其中一辆车的引擎状态,那么另一辆车中的引擎会被修改(因为它是相同的对象引用):
public static void main(String[] args){
Engine eng1 = new Engine("abc");
Car car1 = new Car();
car1.setEngine(eng1);
Car car2 = new Car();
car2.setEngine(car1.getEngine());
//additional code to show the last statement
car2.getEngine().setName("foo");
System.out.println(car2.getEngine().getName()); //prints "foo"
System.out.println(car1.getEngine().getName()); //prints "foo" too
System.out.println(eng1.getName()); //prints "foo" since it is the same object reference used from the beginning
}
点击此处了解如何制作对象引用的副本:Java: recommended solution for deep cloning/copying an instance
答案 4 :(得分:2)
没有深层复制品。两个引用都引用同一个对象尝试使用==运算符来比较两个对象。
Engine eng1 = new Engine("abc");
Car car1 = new Car();
car1.setEngine(eng1); //here you have set the reference eng1 which is pointing to the object abc in heap
Car car2 = new Car();
car2.setEngine(car1.getEngine());// here you are getting the reference of the object which is in the heap and setting it in car2 Object