本文介绍了在Java中处理多个构造函数的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直想知道在Java中处理多个构造函数的最好的(即最干净/最安全/最有效的)方法是什么?特别是当在一个或多个构造函数中不指定所有字段时:
I've been wondering what the best (i.e. cleanest/safest/most efficient) way of handling multiple constructors in Java is? Especially when in one or more constructors not all fields are specified:
public class Book
{
private String title;
private String isbn;
public Book()
{
//nothing specified!
}
public Book(String title)
{
//only title!
}
...
}
$ b b
如果未指定字段,该怎么办?我到目前为止一直在类中使用默认值,以便字段永远不会为空,但是是一种好的做事方式。
What should I do when fields are not specified? I've so far been using default values in the class so that a field is never null, but is that a "good" way of doing things?
推荐答案
略微简化的答案:
public class Book
{
private final String title;
public Book(String title)
{
this.title = title;
}
public Book()
{
this("Default Title");
}
...
}
这篇关于在Java中处理多个构造函数的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!