Nyein Chan
Nyein Chan

Reputation: 1215

Referencing objects in java

In java, what is the difference between following 2 usage,

Employee e1 = new Employee();  
1.Employee e2 = (Employee)e1.clone();  
2.Employee e2 = e1;

In second case, I think e2 reference to the object that e1 also reference. So, they have the same same object with different reference number(may be memory address).

How about first case? Do e1 and e2 have both different object and reference?

Upvotes: 1

Views: 62

Answers (2)

In the first case you are instantiating a new object and store the reference in e1.

suppose you are changing the salary in this next step e1.setSalary(10000);

then if e1 object is cloned, Employee e2 = (Employee)e1.clone(); a new instance with salary as current value stored in e1 will be saved. basically e2 will be a new instance of Employee Class and whose salary is 10000

if you later change the salary of e2 it won't affect e1. e.g.. e2.setSalary(2000); then salary in e1 would remain the same e1 -> 10000 whereas for e2 -> 2000

In the third step, you are referencing e1 to e2,i.e. e2 would point to an instance which was referenced by e1, e1 and e2 would point to same instance... so the cloned object will be like object without reference which is eligible for gc to act upon

For getting to know more about clone, you could refer this post https://stackoverflow.com/a/9834683

Upvotes: 0

meskobalazs
meskobalazs

Reputation: 16041

The first creates a new object by cloning the data of the original object - the class must implement the Clonable interface (a good example is java.util.Calendar).

The second is merely another reference to the same object.

Upvotes: 3

Related Questions