Java 中是否可以根据构造函数调用来初始化最终数据成员?
是否可以按照下面的类中指定的方式进行修改,并将现有调用者的成员初始化为某个默认值,例如null
?
作为持久性要求,成员必须是私有最终。
// 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
}
}
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么你不能直接拥有:
这是构造函数链接的常见模式;让不太具体版本调用更具体版本,并根据需要提供默认参数。
Why can't you just have:
This is the usual pattern for constructor chaining; have the less-specific versions call the more-specific versions, supplying default parameters as appropriate.
是的!
Yes!
是的,这通常用在枚举中。
Yes, This is usually employed in Enums.