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());
}
}
He prints:
1
2
I was expecting a print:
1
1
It seems that on my part there is a fundamental misunderstanding. I expected that the value myObjectbeing the value final staticcannot be changed, and when I do MyClass temp = myObject, I create a new object with a temptype name MyClassand assign a value to myObjectthis newly created object. Please correct me if I am wrong. It seems that the new object is not created, but tempsimply points to the originalmyObject
EDIT: Thanks for the answers! Now I understand that the operator =never makes a copy of the object, it just copies the link. I need to make a copy myObjectand save it to temp. What would be the best way to achieve this?
EDIT2: Java?
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());
}
}
1
4
2
1
, temp new MyClass(33), temp.val = 2, val. , temp.val myObject.val. ?