问题
Is it possible to make a modification as specified in the class below, and initialize a member for existing callers to some default value, say null?
Member is required to be private final as persistence requirement.
// initial version of the class
public class A {
A() {
// do some work here
}
}
// the following modification required adding additional constructor to the class with **member** data member.
public class A {
private final String member;
A(String member) {
this();
this.member = member;
}
A() {
// initilize member to null if a client called this constructor
// do some work here
}
}
回答1:
Why can't you just have:
public class A {
private final String member;
A(String member) {
this.member = member;
}
A() {
this(null);
}
}
This is the usual pattern for constructor chaining; have the less-specific versions call the more-specific versions, supplying default parameters as appropriate.
回答2:
Yes!
public class A {
private final String member;
A(String member) {
this.member = member;
// do some work here instead
}
A() {
this(null);
}
}
回答3:
Yes, This is usually employed in Enums.
来源:https://stackoverflow.com/questions/6225667/is-it-possible-in-java-to-initialise-a-final-data-member-based-on-constructor-ca