An alternative is to use functional programming idiom, and make sure your objects are immutable, by returning a new object.
The idea is the "new object" does not let you modify the field, and the "old object" is creating a new instance (and returning it) instead of simply setting the field, when asked to. This guaranteed your field is still final
, and you can only change it once.
class B {
private static class ValuedB extends B {
public ValuedB(Object obj) {
super(obj);
}
@Override
public Object getObj() {
return super.obj;
}
@Override
public B setObj(Object obj) {
return this;
}
}
public B() {
this(null);
}
private B(Object obj) {
this.obj = obj;
}
private final Object obj;
public Object getObj() { return null;/* or raise exception */ }
public B setObj(Object obj) {
return new ValuedB(obj);
}
}
Invoking with myB = b.setObj(...);
Draw back is of course if you already possess multiple references to an instance of B
, only one will me modified, so if it is the case - this idiom might not fit.
For example, running:
public static void main(String[] args) {
B b = new B();
System.out.println(b.getObj());
b = b.setObj("asdf");
System.out.println(b.getObj());
b = b.setObj("qwerty");
System.out.println(b.getObj());
}
will yield, as expected:
null
asdf
asdf