gpt4 book ai didi

Java:将属性从一个对象实例复制到另一个对象实例?

转载 作者:搜寻专家 更新时间:2023-11-01 04:01:15 25 4
gpt4 key购买 nike

说你有

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 进行深度复制.getEngineer() 并设置为 car2 ?

最佳答案

car1---------------->eng1

car2.setEngine(car1.getEngine());

结果

car1---------------->eng1 <----------------car2

从而指向同一个引擎实例

关于Java:将属性从一个对象实例复制到另一个对象实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21532091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com