Java: copying properties from one object instance to another

Say you have

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

Question: do Car1 and car2 engines refer to the same engine instance, or when I execute car2 When setengine (Car1. Getengine()), it will automatically generate Car1 Getengine() and set it to car2?

Solution

CAR1 —————> ENG1

car2.setEngine(car1.getEngine());

The result is

Car1 -------- > eng1 < ---------------- car2 to point to the same engine instance

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>