My question is very basic, but I would like to understand everything in 100%. Many questions in SO referes to my post, but I haven't find a satisfying answer.
We know that Enums in java are reference type. Let's consider the following snippet:
public static class A {
public int i;
public A(int i) {
this.i = i;
}
}
public static class Test {
int i;
A a;
public Test(int i, A a){
this.i = i;
this.a = a;
}
public Test(Test oldTest){
this.i = oldTest.i;
this.a = oldTest.a;
}
}
public static void main(String[] args) {
Test t1 = new Test(10, new A(100));
System.out.println(t1.i + " " + t1.a.i);
Test t2 = new Test(t1);
t2.i = 200;
t2.a.i = 3983;
System.out.println(t2.i + " " + t2.a.i);
System.out.println(t1.i + " " + t1.a.i);
}
Output is quite obvious because copy constructor of Test makes a shallow copy:
10 100
200 3983
10 3983
BUT because enums in java are also reference types I do not understand one thing. Let's replace A class by Enum:
public static enum TestEnum {
ONE, TWO, THREE;
}
public static class Test {
int i;
TestEnum enumValue;
public Test(int i, TestEnum enumVar){
this.i = i;
this.enumValue = enumVar;
}
public Test(Test oldTest){
this.i = oldTest.i;
this.enumValue = oldTest.enumValue; // WHY IT IS OK ??
}
}
public static void main(String[] args) {
Test t1 = new Test(10, TestEnum.ONE);
System.out.println(t1.i + " " + t1.enumValue);
Test t2 = new Test(t1);
t2.i = 200;
t2.enumValue = TestEnum.THREE; // why t1.emunValue != t2.enumValue ??
System.out.println(t2.i + " " + t2.enumValue);
System.out.println(t1.i + " " + t1.enumValue);
}
I was expecting output:
10 ONE
200 THREE
10 THREE <--- I thought that reference has been copied... not value
But I've got:
10 ONE
200 THREE
10 ONE
Question: Why? Where my thinking is incorrect?