We are all familiar with immutability. A very simple immutable class would be
final class Immutable {
public final float PI = 3.14;
}
Is this truly immutable? Can Java developers really not able to modify PI?
No, they can use the Reflection API to access and modify PI. However, since this is an unorthodox way of accessing a field, although the modification via Reflection API can be blocked with a Security Manager (right?), we say Immutable is immutable even if no Security Manager is activated.
interface ImmutableName {
public String getName();
}
class MutableName implements ImmutableName {
private String name;
public String getName() { return name; }
public void setName(String val) { name = val; }
}
If I have all MutableName instances referred to as ImmutableName instances, the developers modify name. Actually, the developers can check the runtime implementation of the instance then downcast the instance to MutableName. Downcasting is much more common in Java than the Reflection API, but isn't it still some unorthodox trick? Should a class designer code defensively against downcasting?