是否可以按照以下类别中的规定进行修改,并将现有呼叫者的成员初始化为默认值,如null
?是否有可能在Java中基于构造函数调用初始化最终的数据成员?
会员必须是private final作为持久性要求。
// 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
}
}
是的,你可以在构造函数中声明时初始化任何未初始化的最终变量一次。如果您尝试在相同的构造函数或setter方法中再次执行此操作,则会导致编译器错误。 – Arkantos 2014-12-16 21:12:49