Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Object properties does not differ

Tags:

java

ClassName ref = new ClassName();
ref.setCredentials(Credentials);
ref.setVal(value);
ref.setUser(user);

Now when I create a new object of the same class reference, I still get the previous values I have set. Why is this so?

ClassName ref2 = new ClassName();
ref2.setVal(value);
ref2.setUser(user);
ref2.setSomethingNew(somethingNew);

My ref and ref2 instances have all the values [Credentials, Value, User and SomethingNew]. I want to differentiate these two instances. Is it because it's holding the same object?

Update My Lapse:

It's actually ref2 and not ref. I get the values in ref2 which i am not setting, and ref too holds a value which I am setting in the instance of ref2. Both are in same context.

like image 881
theJava Avatar asked May 29 '26 01:05

theJava


1 Answers

Note that with ref2 you are only creating the object, but you are setting the values to ref. You need:

ClassName ref2 = new ClassName();
ref2.setVal(value);
ref2.setUser(user);
ref2.setSomethingNew(somethingNew);

Note the ref2 change instead of ref.

If your ClassName is overriding the equals method, and all the inner objects are equal also, it is normal to have equality between ref and ref2. You can use Object.equals implementation to detect if the objects are different (note different vs. equal).

like image 111
dan Avatar answered May 31 '26 14:05

dan