在Java中是否可以基于构造函数调用来初始化最终数据成员? [英] Is it possible in Java to initialise a final data member based on constructor call?
本文介绍了在Java中是否可以基于构造函数调用来初始化最终数据成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以按照下面类中的指定进行修改,并将现有调用者的成员初始化为某个默认值,例如 null
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
}
}
推荐答案
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.
这篇关于在Java中是否可以基于构造函数调用来初始化最终数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文