Reputation: 3345
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: are the engine of car1 and car2 referring to the same instance of Engine, or when I do car2.setEngine(car1.getEngine())
, it automatically make a deep copy of car1.getEnginer() and set to car2 ?
Upvotes: 3
Views: 2489
Reputation: 85789
As noted by other people, when you do
car2.setEngine(car1.getEngine())
The engine
in car2
will be the same object reference as in car1
. This is easily tested by using ==
:
System.out.println(car2.getEngine() == car1.getEngine()); //prints "true"
when I do
car2.setEngine(car1.getEngine())
it automatically make a deep copy ofcar1.getEngine()
and set tocar2
?
Be careful here, since when executing that statement there's no copy of the object reference, it is not a deep copy nor a shallow copy, it is the same object reference. This means, if you modify the state of the engine in one of the cars, then the engine in the other car gets modified (since is the same object reference):
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
}
Check here to know about how to make copies of object references: Java: recommended solution for deep cloning/copying an instance
Upvotes: 3
Reputation: 1717
There is no deep copy. both reference are refering to same object try to use == operator to compare two objects.
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
Upvotes: 2
Reputation: 803
car1--------------->eng1
car2.setEngine(car1.getEngine());
results in
car1--------------->eng1 <------------------car2
thereby pointing to same engine instance
Upvotes: 6
Reputation: 6408
There is no deep copy. Both Car
instances reference the same instance of Engine
.
Upvotes: 3