One should return so-called "defensive copies" of private reference types. That's to avoid returning the reference of a private field.
I would like to know if that's necessary for private enum types. I read somewhere that enums are immutable reference types, so the answer should be 'no'. Is that right?
In Java, there should only be one instance of each of the values of your enum in memory. A reference to the enum then requires only the storage for that reference. Checking the value of an enum is as efficient as any other reference comparison.
The enums are type-safe means that an enum has its own namespace, we can't assign any other value other than specified in enum constants. Typesafe enums are introduced in Java 1.5 Version. Additionally, an enum is a reference type, which means that it behaves more like a class or an interface.
Enums are used to hold state and are commonly compared, and enum comparisons are incredibly fast. Much, much faster than comparing strings.
I must answer a resounding no because actually you can't. Enums have their own data type and each enum is essentially a new data type.
Enums aren't inherently immutable - but you wouldn't be able to create a defensive copy anyway, as there's only a fixed set of instances available - you'd have to return a reference to one of the existing instances, rather than creating a new instance.
Enums generally should be immutable anyway, but to counteract the claims that they inherently are immutable:
enum BadEnum {
INSTANCE;
private int foo;
private int getFoo() {
return foo;
}
public int setFoo(int foo) {
this.foo = foo;
}
}
class Test {
public static void main(String[] args) {
BadEnum.INSTANCE.setFoo(10);
System.out.println(BadEnum.INSTANCE.getFoo()); // Prints 10
}
}
So in short:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With