I have a class,
class MyClass {
private int val;
public static final MyClass myObject = new MyClass(1);
MyClass(int a){
val = a;
}
public int getVal(){
return val;
}
public MyClass func1(){
MyClass temp = myObject;
temp.val = 2;
return temp;
}
public static void main(String [] args){
MyClass x = new MyClass(4);
System.out.println(myObject.getVal());
x.func1();
System.out.println(myObject.getVal());
}
}
It prints:
1
2
I was expecting it to print:
1
1
There seems to be a fundamental misunderstanding on my part. I was expecting that myObject
being a final static
value cannot be changed, and when I do MyClass temp = myObject
, I create a new object called temp
of type MyClass
and assign the value of myObject
to this newly created object. Please correct me if I am wrong. It seems that the there is no new object created and temp
simply points to the original myObject
EDIT: Thanks for the answers! I now understand that the =
operator never makes a copy of the object, it just copies the reference. What I need is to make a copy of myObject
and store it in temp
. What would be the best way to achieve this?
EDIT2: Another strange behavoir or a feature of Java?
I modified the code slightly
class MyClass {
private Integer val;
public static final MyClass myObject = new MyClass(1);
MyClass(int a){
val = a;
}
public int getVal(){
return val;
}
public MyClass func1(){
MyClass temp = new MyClass(33);
temp.val = myObject.val;
temp.val = 2;
return temp;
}
public static void main(String [] args){
MyClass x = new MyClass(4);
System.out.println(myObject.getVal());
MyClass y = x.func1();
System.out.println(x.getVal());
System.out.println(y.getVal());
System.out.println(myObject.getVal());
}
}
output is
1
4
2
1
Therefore, when I create temp
using new MyClass(33)
and then set temp.val = 2
, it actually makes a copy of val. In other words, temp.val
does not point to myObject.val
. Why is this so?